简体   繁体   中英

Add image to JPanel through JLabel

I want to add an image from imgur onto a JPanel. The image is not appearing.

UTC = new JLabel("test");
utcImg = new ImageIcon("http://i.imgur.com/pkBtKC5.png");
UTC.setIcon(utcImg);
add(UTC);

Only the text "test" is appearing. Am I doing this incorrectly?

Thanks

Edit: Adding image from local drive to mitigate latency issues. Now it's not loading. File is in C:\\Users\\chg1024\\Test\\src\\images

    JLabel utc = new JLabel("test");
    ImageIcon utcImg = new ImageIcon("images/UTC.png");
    utc.setIcon(utcImg);
    add(utc);
    revalidate();

ImageIcon(String) interprets its constructor argument as a file on disk. You could do

URL url = new URL("http://i.imgur.com/pkBtKC5.png");
Image image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));

Note however, that loading images from a URL can create issues due to network latency and/or resource availability. An should be preferred instead, for example

JLabel label = new JLabel(new ImageIcon(getClass().getResource("/images/UTC.png")));

我想你可以用这个

ImageIcon(new URL("write your URL here"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM