Java:如何将图像添加到 Jlabel?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3775373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: how to add image to Jlabel?
提问by KJW
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
采纳答案by Tomas Narros
You have to supply to the JLabel an Icon
implementation (i.e ImageIcon
). You can do it trough the setIcon
method, as in your question, or through the JLabel
constructor:
您必须向 JLabel 提供一个Icon
实现(即ImageIcon
)。您可以通过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
. Also, you can check the How to Use Labels Tutorial, for more information.
我建议你阅读的Javadoc JLabel
,Icon
和ImageIcon
。此外,您可以查看如何使用标签教程,了解更多信息。
回答by Nitesh Verma
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。
回答by mezba z
(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.
(如果您使用的是 NetBeans IDE)只需在您的项目中创建一个文件夹,但在 src 文件夹之外。将文件夹命名为 Images。然后把图片放入Images文件夹,在下面写代码。
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
Now run your program.
现在运行你的程序。
回答by alexlz
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
回答by Adnan Abdollah Zaki
the shortest code is :
最短的代码是:
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURLis PATHof image .
stringPictureURL是image 的路径。