0
  public class Control extends JFrame implements ActionListener {
    javax.swing.Timer timer;
    public Control () {
        timer = new javax.swing.Timer (100, this);
    }

    public static void main(String[] args) {
        new Control();
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == timer) { 
            //some method
        }
        if (e.getActionCommand().equals("Auto")) {
            this.timer.start();
            auto.setText ("Pause");
        }
        if (e.getActionCommand().equals("Pause")) {
            this.timer.stop();
            auto.setText ("Auto");
        }
    }
}

When I press the "Auto" button, the timer runs, but after one instance of the timer, it stops running and presents the follow error message: https://pastebin.com/ExtdqkGa


Yanjiahui
  • 3
  • 1
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – George Z. Mar 15 '19 at 16:35

1 Answers1

1

Try this:

public class Control extends JFrame implements ActionListener {
    javax.swing.Timer timer;
    Button auto;
    public Control () {
        timer = new javax.swing.Timer (100, this);
        auto = new Button("Auto");
        auto.addActionListener(this);
        this.add(auto);
        this.setVisible(true);
        this.setBounds(100,100,100,100);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new Control();
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == timer) {
            System.out.println("Timer finished!");
            return;
        }
        if (e.getActionCommand().equals("Auto")) {
            this.timer.start();
            auto.setLabel("Pause");
        }
        if (e.getActionCommand().equals("Pause")) {
            this.timer.stop();
            auto.setLabel ("Auto");
        }
    }
}

I simply added return to your if statement in the timer block. This is because if timer is the object throwing actionPerformed then e.getActionCommand() will return null.

Timer's do not have actionCommands.

Dylan
  • 1,335
  • 8
  • 21
  • 1
    `Its not a duplicate of that` - well rarely are questions 100% duplicates. The important part of that link in the accepted answer is: [How to pinpoint the exception & cause using Stack Trace](https://stackoverflow.com/q/3988788/2775450). The OP should be able to isolate where the NullPointerException occurs and then ask a more specific question like "why does e.getActionCommand()" return null? Although you solved the problem you haven't given any advice on how to problem solve a NPE in the future. That is the benefit of the provided link. – camickr Mar 15 '19 at 17:00
  • Very well. Thank you for mentoring me. – Dylan Mar 15 '19 at 17:59