2

I am trying to access some images for from image panel using a relative path. In the Eclipse project I have a folder named images with on image inside. Here is my code:

  val top = new MainFrame {

    title = "Predator and Prey Agent simulation"

    val buttonExit = new Button {
      text = "Exit"
      action = Action("Exit") {
        WorldActor.run(false)
        closer
      }
    }

    val buttonStart = new Button {
      text = "Start"
      action = Action("Start") {
        switchPanes()
      }
    }

    val s = new Dimension(500, 700)

    contents = new ImagePanel(0, 1) {
      for (i <- 0 until 5){
        contents+= new Label("")
      }
      contents += buttonStart
      contents += buttonExit
      contents+= new Label("")

      minimumSize = s
      maximumSize = s
      preferredSize = s
      imagePath = ("\\PredatorPrey\\images\\gnp-canadian-lynx-kitten.jpg")

      }
    }

Every time the above code runs I get a javax.imageio.IIOException. Here is the imapePanel class:

case class ImagePanel(rows0: Int, cols0: Int) extends GridPanel(rows0, cols0) {
  private var _imagePath = ""
  private var bufferedImage: BufferedImage = null

  def imagePath = _imagePath

  def imagePath_=(value: String) {
    _imagePath = value
    bufferedImage = ImageIO.read(new File(_imagePath))
  }

  override def paintComponent(g: Graphics2D) = {
    if (null != bufferedImage) g.drawImage(bufferedImage, 0, 0, null)
    }
  }

Does anyone know how to fix that path?

Matthew Kemnetz
  • 845
  • 1
  • 15
  • 28

2 Answers2

4

i just use awt:

import java.awt.Toolkit
val image = Toolkit.getDefaultToolkit.createImage("images/kitten.jpg")

EDIT:

Also, remove \\PredatorPrey\\ from the image path.

EDIT 2: Just explaining what was wrong with the code as cited in the question - when a file path name starts with "/" (or "\" in windows), it becomes absolute ( slash represents the root of the current file system/ drive). Also, the code included the project name in the path. Since the application is run from inside the project, the project directory is not needed in the path (you are already inside that directory!).

aishwarya
  • 1,970
  • 1
  • 14
  • 22
  • Your post helped me the most in fixing the problem, but not exactly because of what you answered. I remembered just after I saw in you post. I needed to remove the project name PredatorPrey AND the initial / from the path declaration. Maybe you can edit your post to say that and I will accept your answer – Matthew Kemnetz Dec 15 '11 at 18:30
1

If you are trying to use a relative path then you need to drop the beginning slash in your path.

imagePath = ("PredatorPrey\\images\\gnp-canadian-lynx-kitten.jpg")
Neil Essy
  • 3,607
  • 1
  • 19
  • 23
  • I tried that exact same thing. When I used the relative path I get an javax.imageio.IIOException: Can't read input file! ecxeption. BUt everything works fine when I use the absolute path. – Matthew Kemnetz Dec 15 '11 at 18:21