简体   繁体   English

通过JLabel将图像添加到JPanel

[英]Add image to JPanel through JLabel

I want to add an image from imgur onto a JPanel. 我想将图像从imgur添加到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. 仅显示文本“ test”。 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 文件位于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. ImageIcon(String)将其构造函数参数解释为磁盘上的文件。 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. 但是请注意,由于网络延迟和/或资源可用性,从URL加载图像可能会产生问题。 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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