By Alvin Alexander. Last updated: December 18, 2017
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 flowLayout.setAlignment(FlowLayout.CENTER) this.setLayout(flowLayout) this.add(imageLabel) // 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.)