How to set image icon in jbutton

I am not very good at creating a Swing application. So I have a question how to set the icon on JButton.

My project structure is as follows:

enter image description here

and I have a simple class JButtonin MainWindow: it looks like this:

tactButton = new JButton("next tact");

and I want to set the image to this button using the method setIcon. My code is as follows:

tactButton.setIcon(new ImageIcon(getClass().getResource("/images/button_next.jpg")));

but when I run the application, I have an exception:

java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at by.bulgak.conveyor.gui.MainWindow.<init>(MainWindow.java:117)
    at by.bulgak.conveyor.gui.MainWindow$1.run(MainWindow.java:46)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

So, I tried different things:

  • put all photos in the same folder as MainWindowclass
  • put images in the root folder of the project
  • try something like tactButton.setIcon(new ImageIcon("/images/button_next.jpg"));

but I have this exception, or if I use tactButton.setIcon(new ImageIcon("/images/button_next.jpg"));, I have a simple button with no image.

, , ( - ). ?

JButton , .

UPDATE

:

tactButton = new JButton("next tact");
tactButton.setSize(100, 100);
tactButton.setIcon(new ImageIcon(MainWindow.class.getResource("/images/button_next.jpg")));
tactButton.addActionListener(new ProcessorNextStepListener(this));
+5
3

Maven, . M2E .

src/main/java

(, ..) src/main/resources

, pom.xml, , . , Maven → ... , " pom.xml"

. .

+4

new ImageIcon(MainWindow.class.getResource("/images/button_next.jpg");

.jpg .png: D

+4

? Eclipse, Maven?

pom.xml , , Maven. Maven, , (.. , .java ) . Maven , . src/main/java src/main/resources. , , src.

.jar, , .

+2

All Articles