【问题标题】:Java: how to add image to Jlabel?Java:如何将图像添加到 Jlabel?
【发布时间】:2010-09-23 04:00:46
【问题描述】:
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)

【问题讨论】:

    标签: java image jlabel


    【解决方案1】:

    您必须向 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,了解更多信息。

    【讨论】:

      【解决方案2】:

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

      ImageIcon imgThisImg = new ImageIcon(PicURL));
      
      jLabel2.setIcon(imgThisImg);
      

      它完全适合我。 PicUrl 是一个字符串变量,用于存储图片的 url。

      【讨论】:

        【解决方案3】:

        (如果您使用的是 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 是图片的PATH

          【讨论】:

            【解决方案5】:

            您可以在 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
            

            【讨论】:

              猜你喜欢
              • 2019-04-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-04-05
              • 1970-01-01
              相关资源
              最近更新 更多