在这个程序中,我们应该点击一个按钮,上面写着"开始"然后动画将开始在屏幕上运行。点击"开始,"按钮然后变为"暂停"按钮,如果你单击它,它会停止动画和"恢复"按钮出现。我不确定如何将所有这三个动作都放在一个按钮上。这是我到目前为止的代码:
htmlInput
我知道这不对。当我运行程序时,动画处于空闲状态,直到我点击"开始"这是正确的,但每次我再次按下按钮时,动画加速,这是不正确的。如何向按钮添加不同的操作?
例如,在动画运行后,我想要"暂停"按钮在单击时停止计时器,然后在我按下"恢复时恢复计时器。"我现在的代码每次单击它时都会创建一个新的Timer对象,但这似乎是我让它工作的唯一方法。如果我在ActionListener之外放置任何东西,我会收到范围错误。有什么建议吗?
答案 0 :(得分:1)
但是每次我再次按下按钮时,动画加速都不正确。
不要在Timer
中继续创建ActionListener
。每次单击该按钮,都会启动一个新的计时器。
而是在类的构造函数中创建Timer
。然后在ActionListener
start()
中Timer
现有的Pause
。
然后现有Timer上的buttons will also just invoke the
和'Resume and
stop()select top 25
companyname, charindex ('A', companyname, 1) as 'occurences of a'
from shippers
restart()`方法。
答案 1 :(得分:1)
我知道这不对。当我运行程序时,动画处于空闲状态,直到我点击“开始”这是正确的,但每次我再次按下按钮时,动画加速,这是不正确的。
这是因为每次按下按钮都会创建多个新的Timer
。您应该只有一个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");
}
}
});