I can't see why my code aren't working. (I'm still learning Java)
Please help me.
The Error / Console:
Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source) at GUI_JButton.Gui.<init>(Gui.java:28) at GUI_JButton.Main.main(Main.java:9)
The main Class:
public static void main(String[] args) { Gui go = new Gui(); //This is need to close the window. go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); go.setSize(300,200); go.setVisible(true); }
The Gui-Class:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; @SuppressWarnings("serial") public class Gui extends JFrame{ private JButton reg; private JButton custom; public Gui(){ //Super is how you call methods form the SUPER-ClASS. It is also how you creat a title. super("The Title"); setLayout(new FlowLayout()); //This is the default layout reg = new JButton("reg Button"); add(reg); //This is how to import photos/icons to the buttons. Icon b = new ImageIcon(getClass().getResource("b.png")); Icon x = new ImageIcon(getClass().getResource("x.png")); //This is the cusotm button. custom = new JButton("Custom", b); custom.setRolloverIcon(x); add(custom); HandlerClass handler = new HandlerClass(); reg.addActionListener(handler); custom.addActionListener(handler); } //When you implement a class, then you have to override all the methodes - Lucky this only has one. private class HandlerClass implements ActionListener{ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand())); } } }
NOTE: I' using a png-file called "b.png" and one called "x.png" - They are both in my "src" / scouce folder - Thanks for your time!