0

I am currently reading through a java book and I have reached a chapter on GUI's.

The book has given example code on how to get a buttons ActionEvent, which I will paste below:

import javax.swing.*;
import java.awt.event.*;

public class SimpleGUI implements ActionListener {

JButton button;

public static void main(String[] args){

    SimpleGUI gui = new SimpleGUI();
    gui.go();

}

public void go(){

    //Create a JFrame and add title
    JFrame frame = new JFrame();
    frame.setTitle("Basic GUI");
    //Create a button with text and add an ActionListener
    JButton button = new JButton("CLICK ME");
    button.addActionListener(this);
    //Add the button to the content pane
    frame.getContentPane().add(button);
    //Set JFrame properties
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

//What should happen when button is pressed
public void actionPerformed(ActionEvent e) {
        button.setText("Button pressed");
    }
}

However, when I run the program and click the button, I get a massive error as follows: (which I have cut short because of space on the post).

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SimpleGUI.actionPerformed(SimpleGUI.java:34)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
......

Could anyone explain why this is not working?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3650602
  • 175
  • 2
  • 10

1 Answers1

0

NullPointerException arise due to global declaration of JButton but it isn't initialize here try like this

public class SimpleGUI implements ActionListener {

JButton button;

public static void main(String[] args) {

    SimpleGUI gui = new SimpleGUI();
    gui.go();

}

private void go() {
    //Create a JFrame and add title
    JFrame frame = new JFrame();
    frame.setTitle("Basic GUI");
    //Create a button with text and add an ActionListener
    button = new JButton("CLICK ME");
    button.addActionListener(this);
    //Add the button to the content pane
    frame.getContentPane().add(button);
    //Set JFrame properties
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent arg0) {
    button.setText("Button Pressed");
}
}
Garg
  • 2,731
  • 2
  • 36
  • 47