Matthew Kemnetz
Matthew Kemnetz

Reputation: 855

Image files and relative paths in scala

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?

Upvotes: 2

Views: 2938

Answers (2)

aishwarya
aishwarya

Reputation: 1986

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!).

Upvotes: 4

Neil Essy
Neil Essy

Reputation: 3607

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")

Upvotes: 1

Related Questions