Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
user2612619 Avatar asked Aug 02 '13 23:08

user2612619


People also ask

Can you put images in Java?

The standard way to access images in a Java application is by using the +getResource()+ method. This tutorial shows you how to use the IDE's GUI Builder to generate the code to include images (and other resources) in your application.

Can you add image to JPanel?

You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()). Save this answer.


3 Answers

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));
like image 61
Rollyng Avatar answered Oct 12 '22 18:10

Rollyng


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.

like image 18
Martijn Courteaux Avatar answered Oct 12 '22 18:10

Martijn Courteaux


If you are using Netbeans to develop, use JLabel and change its icon property.

like image 5
rishad2m8 Avatar answered Oct 12 '22 16:10

rishad2m8