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

28
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
5个回答

36

您需要向JLabel提供一个图标实现(例如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);

我建议您阅读 JLabelIconImageIcon 的Javadoc。 另外,您可以查看How to Use Labels Tutorial以获取更多信息。

25

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

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

这对我完全有效。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);

现在运行你的程序。


4
最短的代码是:
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL是图片的路径


1

一个简单的代码,你可以在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接