Java: how to add image to Jlabel?

后端 未结 5 551
悲哀的现实
悲哀的现实 2020-11-28 12:45
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
相关标签:
5条回答
  • 2020-11-28 13:06

    (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.

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

    Now run your program.

    0 讨论(0)
  • 2020-11-28 13:10

    the shortest code is :

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

    stringPictureURL is PATH of image .

    0 讨论(0)
  • 2020-11-28 13:11

    To get an image from a URL we can use the following code:

    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.

    0 讨论(0)
  • 2020-11-28 13:12

    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:

    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.

    0 讨论(0)
  • 2020-11-28 13:18

    Simple code that you can write in main(String[] args) function

        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
    
    0 讨论(0)
提交回复
热议问题