I have an application with a Swing GUI and I would like to add a search-field with a search-button (lupe icon) to the menu bar. However, the lupe icon won't display. Here is my code:
public class Ui_Frame {
public static void main(String[] args) {
SwingUtilities.invokeLater(Ui_Frame::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Myframe");
...
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon("Resources/lupe_icon.png");
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
...
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
My project structure is like
Project
Src
Ui_Frame.java
Resources
lupe_icon.png
The resulting button shows no icon at all :
I do not get any error message, it compiles without problems. Even when I try to catch any exception from the new ImageIcon(...) I'm not getting any hint at what the error is.
Any ideas as to what Im doing wrong here?
EDIT:
Here is a minimal example:
import javax.swing.*;
public class test {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(test::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon(test.class.getResource("/Resources/lupe_icon.png"));
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(500,500);
f.setVisible(true);
}
}
As you can see I am now loading the image with class.getResource(...) as was suggested by @AndrewThompson and @SergiyMedvynskyy, but that does not solve the problem. Also I was told that my classes should not be static, but since my Main needs to be static for me to be able to run the program and I have been told that I should start the UI with SwingUtilities.invokeLater(test::createAndShowGUI);
which also forces createAndShowGUI() to be static, I do not know how to make it not static.