Reputation: 1
I'm new to Swing and just need to know how to place an image on the home screen of my GUI. I don't want it to be the background. When my lecturer demoed it I think he placed it inside a JLabel. I saved the image to my laptop, but do I need to import it into the project I'm working on in Eclipse? If so, where is the best place to save it to? Thanks.
Upvotes: 0
Views: 1580
Reputation: 46841
Put all the images in images
folder that you have in your project in parallel to src
folder.
F:/>Kiosk
|
|___src
|
|__main1.java
|
|__images
|
|__c.jpg
|__d.jpg
|__e.jpg
|__f.jpg
Use this code
ImageIO.read(new File("images\\c.jpg"));
ImageIO.read(new File("images\\d.jpg"));
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
All the above method returns BufferedImage
.
How to convert
BufferedImage
intoImageIcon
?
BufferedImage image = ImageIO.read(new File("images\\c.jpg"));
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
Upvotes: 3
Reputation: 192
Create an image subdirectory within your Eclipse project and copy the graphic to that folder. Then, extend JPanel something like this:
class MyImagePanel extends JPanel {
private ImageIcon imageIcon = new ImageIcon("image/myimage.gif");
private Image image = imageIcon.getImage();
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) g.drawImage(image,0,0,getWidth(),getHeight(),this);
}
}
from there, you can add this panel to your main JFrame using:
add(new MyImagePanel());
Upvotes: 0