javaimageswingbackgroundjframe

Adding image to JFrame


So I am using Eclipse with Windows builder. I was just wondering if there was anyway I can import an image that'll show up on the JFrame that I can easily move around and re-size instead of setting the location and size and drawing it.


Solution

  • There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

    1. As @Reimeus said: Use a JLabel with an icon.
    2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

      JImageComponent ic = new JImageComponent(myImageGoesHere);
      imagePanel.add(ic);
      

      where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.