简体   繁体   English

使用 URL (Java) 将图像加载到 JPanel

[英]Load Image Into JPanel With URL (Java)

I'm currently working on a Java school project where I have to display an image into a JPanel.我目前正在从事一个 Java 学校项目,我必须将图像显示到 JPanel 中。 I'm having some trouble loading the image.我在加载图像时遇到了一些问题。 Here's my code:这是我的代码:

public void LoadImage(String imageURL){
    panel.setLayout(new BorderLayout());

    Image image = null;
    URL url = null;
    try {
        url = new URL("https://i.ibb.co/GTTV1cm/3ad25e3ae0f6.jpg");

        image = ImageIO.read(url);
        JLabel label = new JLabel(new ImageIcon(image));
        panel.add(label, BorderLayout.CENTER);
    } catch (MalformedURLException ex) {
        System.out.println("Malformed URL");
    } catch (IOException iox) {
        System.out.println("Can not load file");
        iox.printStackTrace();
    }

    pack();
    setVisible(true);
}

And this is the error I'm getting这是我得到的错误

javax.imageio.IIOException: Can't get input stream from URL!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1409)
at MainScreen.LoadImage(MainScreen.java:90)
at MainScreen.<init>(MainScreen.java:35)
at MainScreen.main(MainScreen.java:105)
Caused by: java.io.FileNotFoundException: https://i.ibb.co/GTTV1cm/3ad25e3ae0f6.jpg
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1993)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)
    at java.base/java.net.URL.openStream(URL.java:1161)
    at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1407)
    ... 3 more

I would greatly appreciate your help as I'm a beginner in Java!!非常感谢您的帮助,因为我是 Java 的初学者!

There seems to be some confusion ( at least for me and by reading the comments ) as to what the actual URL is to the image you are trying to access on the net.对于您尝试在网络上访问的图像的实际 URL 是什么,似乎存在一些混淆(至少对我而言,并且通过阅读评论)。 With the URL supplied ( https://i.ibb.co/GTTV1cm/3ad25e3ae0f6.jpg ) I get a blank black page with the following image (yes...I said image) sitting in the middle:使用提供的 URL ( https://i.ibb.co/GTTV1cm/3ad25e3ae0f6.jpg ) 我得到一个空白的黑色页面,中间有下面的图像(是的......我说的是图像):

在此处输入图像描述

To me, this means there is no image at the URL provided so, the URL is invalid.对我来说,这意味着提供的 URL中没有图像,因此 URL 无效。 Uhhhh, confusion ended.呵呵,混乱结束了。

Anyways, I just wanted to suggest that you let your loadImage() method do exactly that, load an image and leave the GUI building in another method altogether.无论如何,我只是想建议您让您的loadImage()方法完全做到这一点,加载图像并将 GUI 构建完全保留在另一种方法中。 Either have this method return an ImageIcon which can be set into a component during the GUI build or set the image to the component itself within the method by passing the component as argument after the GUI build.要么让这个方法返回一个ImageIcon ,它可以在 GUI 构建期间设置到组件中,要么在方法内通过在 GUI 构建之后将组件作为参数传递来将图像设置为组件本身。

The method below requires the JLabel to be passed to it in order load an image into it.下面的方法需要将 JLabel 传递给它,以便将图像加载到其中。 The image path supplied can be from an URL, resources, or local file system.提供的图像路径可以来自 URL、资源或本地文件系统。 It shouldn't matter if the url is http or https . url 是http还是https无关紧要。 The method also contains an option to size the image to the actual JLabel or not.该方法还包含将图像大小调整为实际 JLabel 或不调整大小的选项。

/**
 * Loads an image into the supplied JLabel.<br><br>
 *
 * @param jlabel                  (JLabel) The variable name of the JLabel
 *                                to load image into<br>
 *
 * @param imagePath               (String) The full path and file name of
 *                                the image to load into JLabel. This path
 *                                can be either from the local file system
 *                                or from a from a JAR's resources or from a
 *                                http or https web link, for example:<pre>
 *
 *      "C:/My Gifs/flowers.gif"
 *
 *                OR
 *
 *      "/resources/images/flowers.gif"
 *
 *                OR
 *
 *      "https://thumbs.gfycat.com/cool.gif"</pre>
 *
 * To retrieve your images from a JAR's resources you need to ensure that
 * your resource folder is properly located during development. The resource
 * folder (resources) should be located within the source (src) folder. The
 * path tree should be:
 * <pre>
 *
 *  * PROJECT NAME
 *      * src
 *          * PACKAGE YOU NAMED IN PROJECT
 *               yourApp.java
 *          * resources
 *              * images
 *                  yourImageFile1.jpg
 *                  yourImageFile2.gif
 *                  yourImageFile3.png
 *                  yourImageFile4.jpeg
 *                  yourImageFile5.bmp
 *                  yourImageFile6.wbmp
 *              * text
 *                  myText1.txt
 *                  myText2.txt
 *                  myText3.txt
 *              * etc..........</pre>
 *
 * Whenever loading anything from resources the path must always start with
 * a forward slash (/), for example:
 * <pre>
 *
 *      loadImageToJLabel(jLabel1, "/resources/inages/yourImageFile1.jpg", true);</pre>
 *
 * @param autoSetImageToLabelSize
 */
public void loadImageToJLabel(JLabel jlabel, String imagePath, boolean... autoSetImageToLabelSize) {
    String ls = System.lineSeparator();
    boolean autoSize = false;
    if (autoSetImageToLabelSize.length > 0) {
        autoSize = autoSetImageToLabelSize[0];
    }
    javax.swing.ImageIcon image;

    try {
        if (imagePath.toLowerCase().startsWith("http")) {
            final java.net.URL url = new java.net.URL(imagePath);
            java.net.HttpURLConnection huc = (java.net.HttpURLConnection) url.openConnection();
            int responseCode = huc.getResponseCode();
            huc.disconnect();
            //Does responseCode fall into the 200 to 299 range (which are the codes for: SUCCESS)
            // If NO then....
            if (responseCode < 200 || responseCode > 299) {
                System.err.println("loadImageToJLabel() Method Error! Can not "
                        + "locate the image file specified!" + ls + "Ensure "
                        + "that your HTTP or HTTPS link exists!" + ls
                        + "Supplied Link Path:  \"" + imagePath + "\"" + ls);
                return;
            }
            image = new javax.swing.ImageIcon(url); //new URL(imagePath));
        }
        else if (imagePath.startsWith("/") || imagePath.startsWith("\\")) {
            Class currentClass = new Object() {
            }.getClass().getEnclosingClass();
            try {
                image = new javax.swing.ImageIcon(currentClass.getClass().getResource(imagePath));
            }
            catch (NullPointerException npe) {
                System.err.println("loadImageToJLabel() Method Error! Can not "
                        + "locate the Resource Path or the resource file!" + ls + "Ensure "
                        + "that your resources are properly located." + ls
                        + "Supplied Resource Path:  \"" + imagePath + "\"" + ls);
                return;
            }
        }
        else {
            java.io.File f = new java.io.File(imagePath);
            if (!f.exists()) {
                System.err.println("loadImageToJLabel() Method Error! Can not "
                        + "locate the image file specified!" + ls + "Ensure "
                        + "that your Image file exists within the local file system path provided!" + ls
                        + "Supplied File Path:  \"" + imagePath + "\"" + ls);
                return;
            }
            image = new javax.swing.ImageIcon(new java.net.URL("file:" + imagePath));
        }

        if (autoSize) {
            Image img = image.getImage();
            Image resizedImage = img.getScaledInstance(jlabel.getWidth(), jlabel.getHeight(), java.awt.Image.SCALE_SMOOTH);
            jlabel.setIcon(new ImageIcon(resizedImage));
        }
        else {
            jlabel.setIcon(image);
        }
        jlabel.validate();
    }
    catch (java.net.MalformedURLException ex) {
        System.err.println("loadImageToJLabel() Method Error! Improper Image file link supplied!" + ls
                + "Supplied Link:  \"" + imagePath + "\"" + ls);

    }
    catch (java.io.IOException ex) {
        System.err.println("loadImageToJLabel() Method Error! Can not access Image File!" + ls
                + "Supplied File Path:  \"" + imagePath + "\"" + ls);
    }
}

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

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