kinkajou
kinkajou

Reputation: 3728

Rendering Image into label

I have a label. I want to render image into it. But the following code would do anything.

 CardLayout cl = (CardLayout) (mainPanel.getLayout());
        cl.show(mainPanel, "newPersonaCard");
        BufferedImage myPicture = ImageIO.read(new    File("C:\\Desktop\\Documents\\Pictures\\always.jpg"));
        ImageIcon icon = new ImageIcon(myPicture);
        icon.getImage().flush();

I am using netbean designer.

Upvotes: 1

Views: 527

Answers (3)

eabraham
eabraham

Reputation: 4164

fileChooser.showDialog(saveBtn2, null);
File file = fileChooser.getSelectedFile();
System.out.println("The path to file "+file.getAbsolutePath());          
ImageIcon icon = new ImageIcon(file.getAbsolutePath());
pictureLbl.setIcon(icon);

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

You are right, in some cases there issue with repainting Icon in the JLabel, then you have to call,

myIcon.getImage().flush();
myLabel.setIcon(myIcon);

rest of methods is implemented in the Icon and JLabel correctly

Upvotes: 1

Sully
Sully

Reputation: 14943

.
.
File file = fileChooser.getSelectedFile();

JLabel label = new JLabel();
ImageIcon icon = new ImageIcon(file.getAbsolutePath());
label.setIcon(icon);
//add label to panel

Upvotes: 1

Related Questions