Scala Swing: An ImageIcon, JLabel, and JPanel example

If you ever need to add an image to a Scala/Java Swing application, I hope this example will help. It shows how to create an ImageIcon using getResource, then add that image to a JLabel, then add that label to a JPanel:

class MicrophonePanel extends JPanel {

  val micImage = new ImageIcon(classOf[com.devdaily.sarah.Sarah].getResource("microphone-image.png"))
  val imageLabel = new JLabel(micImage)
  val flowLayout = new FlowLayout
  // more code here ...

There may be better ways to do this, but this is the most simple way I know.

In a Scala/SBT project, this approach works if the image file (PNG) is located in the src/main/resources/com/devdaily/sarah folder of your project. (There might be a better way to do this as well.)

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.