Java Swing计时器第一实例崩溃

Java Swing计时器第一实例崩溃,java,swing,timer,Java,Swing,Timer,当我按下自动按钮时,计时器运行,但在计时器的一个实例之后,它停止运行并显示以下错误消息: 试试这个: public class Control extends JFrame implements ActionListener { javax.swing.Timer timer; public Control () { timer = new javax.swing.Timer (100, this); } public static voi

当我按下自动按钮时,计时器运行,但在计时器的一个实例之后,它停止运行并显示以下错误消息:

试试这个:

  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");
        }
    }
}
我只是将return添加到计时器块中的if语句中。这是因为如果timer是抛出actionPerformed的对象,则e.getActionCommand将返回null


计时器没有actionCommands。

它可能重复,而不是重复-问题很少是100%重复的。公认答案中该链接的重要部分是:。OP应该能够隔离NullPointerException发生的位置,然后问一个更具体的问题,比如e.getActionCommand为什么返回null?虽然你已经解决了这个问题,但你还没有给出任何关于如何解决未来NPE问题的建议。这就是提供链接的好处。非常好。谢谢你指导我。
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");
        }
    }
}