gpt4 book ai didi

java - JButton 中的多个操作

转载 作者:行者123 更新时间:2023-12-02 04:19:09 26 4
gpt4 key购买 nike

在这个程序中,我们应该单击一个“开始”按钮,然后动画将开始在屏幕上运行。单击“开始”后,该按钮将更改为“暂停”按钮,如果单击它,它将停止动画并出现“恢复”按钮。我不知道如何将所有这三个操作整合到一个按钮中。这是我到目前为止的代码:

JButton button = new JButton("Start");
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Timer t = new Timer(100, new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
shape.translate(x, y);
label.repaint();
}
});
t.start();
}
});

我知道这是不对的。当我运行程序时,动画处于空闲状态,直到我点击“开始”,这是正确的,但每次我再次点击按钮时,动画都会加速,这是不正确的。如何向按钮添加不同的操作?

例如,在动画运行后,我希望“暂停”按钮在单击时停止计时器,然后在单击“恢复”时恢复计时器。我现在的代码每次单击它时都会创建一个新的 Timer 对象,但这似乎是我让它工作的唯一方法。如果我在 ActionListener 之外放置任何内容,则会出现范围错误。有什么建议吗?

最佳答案

I know this isn't right. When I run the program, the animation is idle until I hit "Start" which is correct, but then every time I hit the button again, the animation speeds up which is not correct.

这是因为每次按下按钮时都会创建多个新的计时器。您应该对 Timer 有一个引用,并根据其当前状态决定要做什么

//...
private Timer timer;
//...

JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (timer == null) {
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent event) {
shape.translate(x, y);
label.repaint();
}
});
timer.start();
button.setText("Pause");
} else if (timer.isRunning()) {
timer.stop();
button.setText("Resume");
} else {
timer.start();
button.setText("Pause");
}
}
});

关于java - JButton 中的多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com