Java:如何将图像添加到Jlabel?

KJW*_*KJW 23 java image jlabel

Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
Run Code Online (Sandbox Code Playgroud)

Tom*_*ros 29

您必须向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);
Run Code Online (Sandbox Code Playgroud)

我建议你阅读的Javadoc JLabel,IconImageIcon.此外,您还可以查看如何使用标签教程,以获取更多信息.


Nit*_*rma 24

要从URL获取图像,我们可以使用以下代码:

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);
Run Code Online (Sandbox Code Playgroud)

它完全适合我.PicUrl是一个字符串变量,用于绘制图片的url.


小智 12

(如果您使用的是NetBeans IDE)只需在项目中创建一个文件夹,但在src文件夹的一侧.将文件夹命名为Images.然后将图像放入Images文件夹并在下面编写代码.

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
Run Code Online (Sandbox Code Playgroud)

现在运行你的程序.