简体   繁体   English

需要帮助来停止我的 Java Swing GUI 计时器吗?

[英]Need help to stop my Java Swing GUI timer?

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;导入 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.提前致谢。

the problem is that endbut dosen't has action listener, so when the button is get clicked nothing is happen t.stop();问题是 endbut 没有动作监听器,所以当按钮被点击时什么也没有发生 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 到同一个动作监听器,这样当它被点击时 actionPerformed 被调用(t.stop)

endbut.addActionListener(this);

after

// TODO Auto-generated method stub
    startbut.addActionListener(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM