Java Swing Timer第一个实例崩溃

时间:2019-03-15 16:30:48

标签: 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 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


1 个答案:

答案 0 :(得分:1)

尝试一下:

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。