Wie die Bild-icon auf JButton

Ich bin nicht sehr gut im erstellen von Swing-Anwendung. Also ich habe eine Frage, wie man set-Symbol, um JButton.

Meine Projektstruktur sieht wie folgt aus:

Wie die Bild-icon auf JButton

und ich habe einfach JButton im MainWindow Klasse:
es sieht wie folgt aus:

tactButton = new JButton("next tact");

und ich möchte, um Bild zu diesem button mit der Methode setIcon. Mein code sieht wie folgt aus:

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

aber wenn ich starten app, die ich haben Ausnahme:

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)

Also habe ich verschiedene Sachen ausprobiert:

  • setzen Sie alle Bilder in den gleichen Ordner wie MainWindow Klasse
  • stellen Bilder in der Projekt-root-Ordner
  • versuchen so etwas wie tactButton.setIcon(new ImageIcon("/images/button_next.jpg"));

aber ich habe diese Ausnahme oder wenn ich tactButton.setIcon(new ImageIcon("/images/button_next.jpg")); ich habe einfach-Taste ohne Bild.

Schließlich schrieb ich den absoluten Pfad zu meinem Bild und das funktioniert gut (aber absolute Pfad ist keine gute Idee). Also könnt Ihr mir bitte helfen?

Schaute ich mir die Frage Wie füge ich ein Bild auf einem JButton und versucht, es zu tun, wie es.

UPDATE

Vollständigen code zu erstellen-Taste und set-Symbol:

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));

InformationsquelleAutor Aleksei Bulgak | 2013-02-18

Schreibe einen Kommentar