简体   繁体   中英

why isn't .getFile() loading image

NEW Update

Have now done a different thing and got more than one image to appear in the JFrame at one time, but importantly how do I equally space the images horizontally?

package test;

import java.net.URL;

import javax.swing.*;

public class Test {
    
    public static void main(String[] args) {
    
    String[] list = {"test/Spidey.jpg","test/mandarin.jpg","test/jaws.jpg"};
    JFrame window = new JFrame();
    
    for(int i=0; i<list.length; i++) {
    

    
    URL myurl = Test.class.getClassLoader().getResource(list[i]);
    ImageIcon img = new ImageIcon(myurl);
    JLabel l = new JLabel(img);
    
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.add(l);
    window.pack();
    window.setVisible(true);
    
        }
    }
}

Update:

Got it working like this:


import javax.swing.*;

public class Test {
    
    public static void main(String[] args) {
    
    JFrame window = new JFrame();
    ClassLoader theClass = spidey.class.getClassLoader();
    URL myurl = theClass.getResource("test/Spidey.jpg");
    ImageIcon img = new ImageIcon(myurl);
    JLabel l = new JLabel(img);
    
    
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.add(l);
    window.pack();
    window.setVisible(true);
    
    }
}

Almost the same as before, but this time added ImageIcon

To display image in JLabel you must use JLabel(Icon i); But here the getFile() method you used will only return the name of the file. Try the following

URL url = new URL("your desired url");
Image img = ImageIO.read(url);
l.setIcon(new ImageIcon(img));

The problem is with the following line:

ClassLoader theClass = spidey.class.getClassLoader();

It should be

ClassLoader theClass = Test.class.getClassLoader();

You can also write it in one line as follows:

URL myurl = Test.class.getClassLoader().getResource("resources/IMG_20191230_153117.jpg");

According to the code you posted, file Spidey.jpg needs to be in the same directory as file spidey.class .

Method getResource() is returning null. Hence variable imageURL is null. Hence this part of your code is throwing NullPOinterException :

imageURL.getFile()

EDIT

Class<?> theClass = spidey.class;
URL url = theClass.getResource("Spidey.jpg");
ImageIcon img = new ImageIcon(url);
JLabel l = new JLabel(img);

Refer to How to Use Icons in the Java Tutorials

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