Reputation: 1
I'm trying to add an image to a JLabel to put on JFrame and after hours of researching it still only loads the JFrame with 2 buttons on the bottom. The Image in question is in the same directory as the class except a folder down (I've tried in the same folder to no avail). I'm quite new to coding so please bear with me.
This is most of the code except the button's action listeners (the class extends JFrame as well)
JPanel jp = new JPanel();
JPanel jb = new JPanel(new GridLayout(1, 2, 20, 20));
JLabel jl = new JLabel();
JButton end = new JButton("End");
JButton next = new JButton("Next");
jl.setIcon(new ImageIcon("notes/daWay.jpg"));
setSize(900, 700);
jp.add(jl, new FlowLayout());
add(jp);
jb.add(end);
jb.add(next);
add(jb, BorderLayout.PAGE_END);
setVisible(true);
I've tried: setting label bounds, checked if ImageIcon was null (it wasn't), making ImageIcon its own variable then adding the variable to the Jlabel, getContentPane for JFrame, using a BufferedImage and ImageIO with try and catch (with url and without), getClass, getClassLoader, getResource, imageUpdate on the label, with FlowLayout and without, jpegs and pngs, clearing the frame except for the one label, and many other things. Even extending the window while running the image doesn't appear, Please Help!
(also in the future I'd like to clear the label and add a new image, I'm not at that point yet cause I can't get past this error but if context helps with the solution then context)
Upvotes: 0
Views: 146
Reputation: 692121
The ImageIcon constructor you're using takes a file path as an argument.
For your code to work, you would thus have to pass an absolute file path, because relative ones are resolved based on the current directory, not based on the class containing the file path.
The current directory is the directory from which the java command is executed.
What you want to do is use the class loader to load the image. So that you can embed the image into the jar file you will create when building your application.
So you should instead use
new ImageIcon(YourClass.class.getResource("notes/daWay.jpg"))
This will load the image from the daWay.jpg resource located in the subpackage notes
of the package of YourClass
.
Upvotes: 2