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

时间:2010-09-23 04:00:47

标签: java image jlabel

Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)

5 个答案:

答案 0 :(得分:27)

您必须向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);

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

答案 1 :(得分:23)

要从网址获取图片,我们可以使用以下代码:

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

这完全适合我。 PicUrl是一个字符串变量,用于绘制图片的网址。

答案 2 :(得分:12)

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

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

现在运行你的程序。

答案 3 :(得分:3)

最短的代码是:

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL 是图片的路径

答案 4 :(得分: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