简体   繁体   中英

unable to set image in JLabel

I designed one simple Form.

In which i put one panel as contentPane one JLabel as lblPanel.

now i am trying to set image in JLabel.

I am having WindowBuilder so i can directly set image using setting the icon property of JLabel.

But when i try this it shows the Image only as its original size which is natural we must have to manually set image size to fed the JLabel whole.

SO, here is the Code that is generated by the WindowBuilder when i set the Image using the icon properties of JLabel.

lblPanel.setIcon(new ImageIcon(Admin_Form.class.getResource("/Icons/MouthSmile.jpg")));

Now My Problem is i want to set the size of image as the size of JLabel so there is any direct way to do it using WindowBuilder or just Modifying the above line?

I also tried the following way in which i taken two Imageicon and one Image.

Here is the code for that that i have been tried.

private Image img;
private ImageIcon imgicon;
private ImageIcon newimgicon;

imgicon = new ImageIcon("/Icons/MouthSmile.jpg");
img = imgicon.getImage();

newimgicon = new ImageIcon(img.getScaledInstance(lblPanel.getWidth(),lblPanel.getHeight(), Image.SCALE_SMOOTH)); 
lblPanel.setIcon(newimgicon);

But when i remove the code that is generated by the Window Builder and use only mine the image is not displayed.

I also seen the way to do it using BufferedImage but i think there will be no difference wheather i will use BufferedImage to resize or ImageIcon and Image.

如果您尝试在将lblPanel添加到Container之前以及在看到JFrame之前获取lblPanel的宽度和高度,则宽度和高度都将为0。

You can resize the image you are choosing to use which will make the JLabel the size you desire. That is the simplest way of going about doing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM