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


当我按下“自动”按钮时,计时器运行,但是在计时器的一个实例之后,它将停止运行并显示以下错误消息:
https://pastebin.com/ExtdqkGa

最佳答案

尝试这个:

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


我只是在计时器块的if语句中添加了return。这是因为如果timer是抛出actionPerformed的对象,则e.getActionCommand()将返回null。

计时器没有actionCommands。

07-28 00:02