英文:
Need help to stop my Java Swing GUI timer?
问题
我想通过点击按钮来启动和停止我的计时器。但是停止按钮无法正常工作。我该如何修复这个问题?
我正在处理一个包含计时器和其他功能的项目。我想做的就是通过使用按钮来启动和停止我的计时器。
import javax.swing.Timer;
JButton startbut = new JButton("开始");
JButton endbut = new JButton("标记为完成");
private void addActionEvent() {
// TODO Auto-generated method stub
startbut.addActionListener(this);
}
int s = 0, h = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startbut) {
t = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
time.setText(String.valueOf(h + "m:" + s + "s"));
s++;
if (s == 60) {
h++;
s = 0;
}
}
});
t.start();
}
if (e.getSource() == endbut) {
t.stop();
}
}
提前感谢。
英文:
I want to start and stop my timer by clicking buttons. But the stop button doesn't work. How should I fix this?
I'm working on a project which contains a Timer along with other features. All I want to do is Start and Stop my timer by using Buttons.
import javax.swing.Timer;
JButton startbut=new JButton("Start");
JButton endbut=new JButton("Mark As Done");
private void addActionEvent() {
// TODO Auto-generated method stub
startbut.addActionListener(this);
}
int s=0,h=0;
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==startbut) {
t=new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
time.setText(String.valueOf(h+"m:"+s+"s"));
s++;
if(s==60) {
h++;
s=0;
}
}
});
t.start();
}
if(e.getSource()==endbut) {
t.stop();
}
}
Thanks in Advance.
答案1
得分: 0
问题在于 endbut
没有添加动作监听器,因此当按钮被点击时没有任何反应,t.stop();
从未被调用。我们需要将 endbut
注册到相同的动作监听器,这样当它被点击时会调用 actionPerformed
方法(停止 t
)。
endbut.addActionListener(this);
在此之后:
// TODO 自动生成的方法存根
startbut.addActionListener(this);
英文:
the problem is that endbut dosen't has action listener, so when the button is get clicked nothing is happen t.stop(); never get call. we need to register endbut to the same action listenerd so that when it get clicked actionPerformed is get called (t.stop)
endbut.addActionListener(this);
after
// TODO Auto-generated method stub
startbut.addActionListener(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论