[英]Java: how to add image to Jlabel?
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
You have to supply to the JLabel an Icon
implementation (ie ImageIcon
).您必须为 JLabel 提供一个
Icon
实现(即ImageIcon
)。 You can do it trough the setIcon
method, as in your question, or through the JLabel
constructor:您可以通过
setIcon
方法(如您的问题)或通过JLabel
构造函数来完成:
Image image=GenerateImage.toImage(true); //this generates an image file
ImageIcon icon = new ImageIcon(image);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
I recommend you to read the Javadoc for JLabel
, Icon
, and ImageIcon
.我建议您阅读
JLabel
、 Icon
和ImageIcon
的 Javadoc。 Also, you can check the How to Use Labels Tutorial , for more information.此外,您可以查看如何使用标签教程,了解更多信息。
To get an image from a URL we can use the following code:要从 URL 获取图像,我们可以使用以下代码:
ImageIcon imgThisImg = new ImageIcon(PicURL));
jLabel2.setIcon(imgThisImg);
It totally works for me.它完全适合我。 The PicUrl is a string variable which strores the url of the picture.
PicUrl 是一个字符串变量,它存储图片的 url。
(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. (如果您使用的是 NetBeans IDE)只需在您的项目中创建一个文件夹,但在 src 文件夹之外。 Named the folder Images.
将文件夹命名为 Images。 And then put the image into the Images folder and write code below.
然后把图片放入Images文件夹,在下面写代码。
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
Now run your program.现在运行你的程序。
the shortest code is :最短的代码是:
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL is PATH of image . stringPictureURL是 image 的路径。
Simple code that you can write in main(String[] args) function您可以在main(String[] args)函数中编写的简单代码
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
frame.setSize(800,600);
frame.setLocation(200,200);
JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
JLabel label = new JLabel();
label.setIcon(new ImageIcon(img));
frame.getContentPane().add(label);
}
frame.setVisible(true);//showing up the frame
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.