需要帮助停止我的Java Swing GUI定时器。

huangapple go评论105阅读模式
英文:

Need help to stop my Java Swing GUI timer?

问题

我想通过点击按钮来启动和停止我的计时器。但是停止按钮无法正常工作。我该如何修复这个问题?

我正在处理一个包含计时器和其他功能的项目。我想做的就是通过使用按钮来启动和停止我的计时器。

  1. import javax.swing.Timer;
  2. JButton startbut = new JButton("开始");
  3. JButton endbut = new JButton("标记为完成");
  4. private void addActionEvent() {
  5. // TODO Auto-generated method stub
  6. startbut.addActionListener(this);
  7. }
  8. int s = 0, h = 0;
  9. @Override
  10. public void actionPerformed(ActionEvent e) {
  11. if (e.getSource() == startbut) {
  12. t = new Timer(100, new ActionListener() {
  13. @Override
  14. public void actionPerformed(ActionEvent e) {
  15. time.setText(String.valueOf(h + "m:" + s + "s"));
  16. s++;
  17. if (s == 60) {
  18. h++;
  19. s = 0;
  20. }
  21. }
  22. });
  23. t.start();
  24. }
  25. if (e.getSource() == endbut) {
  26. t.stop();
  27. }
  28. }

提前感谢。

英文:

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;

  1. JButton startbut=new JButton("Start");
  2. JButton endbut=new JButton("Mark As Done");
  3. private void addActionEvent() {
  4. // TODO Auto-generated method stub
  5. startbut.addActionListener(this);
  6. }
  7. int s=0,h=0;
  8. @Override
  9. public void actionPerformed(ActionEvent e) {
  10. if(e.getSource()==startbut) {
  11. t=new Timer(100, new ActionListener() {
  12. @Override
  13. public void actionPerformed(ActionEvent e) {
  14. time.setText(String.valueOf(h+"m:"+s+"s"));
  15. s++;
  16. if(s==60) {
  17. h++;
  18. s=0;
  19. }
  20. }
  21. });
  22. t.start();
  23. }
  24. if(e.getSource()==endbut) {
  25. t.stop();
  26. }
  27. }

Thanks in Advance.

答案1

得分: 0

问题在于 endbut 没有添加动作监听器,因此当按钮被点击时没有任何反应,t.stop(); 从未被调用。我们需要将 endbut 注册到相同的动作监听器,这样当它被点击时会调用 actionPerformed 方法(停止 t)。

  1. endbut.addActionListener(this);

在此之后:

  1. // TODO 自动生成的方法存根
  2. 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)

  1. endbut.addActionListener(this);

after

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

huangapple
  • 本文由 发表于 2020年9月22日 23:22:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64012812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定