开始计时器(javax.swing)在按钮点击时而不是自行启动

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

Start timer (javax.swing) on button-click rather than on its own

问题

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;

public class Main extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 550;
    public static final int HEIGHT = 550;
    public static final int WIDTH1 = 450;
    public static final int HEIGHT1 = 450;
    public static final int WIDTH2 = 125;
    public static final int HEIGHT2 = 25;

    private JLabel lblValue;
    private int clicks = 0;
    private int count = 6;

    public static void main(String[] args)
    {
        Main counter1 = new Main( );
        counter1.setVisible(true);

        Main counter2 = new Main( );
        counter2.setVisible(true);
    }

    public Main( )
    {
        setTitle("CPS Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(WIDTH, HEIGHT);
        setMaximumSize(new Dimension(WIDTH, HEIGHT));
        setMinimumSize(new Dimension(WIDTH, HEIGHT));
        setLayout(new FlowLayout( ));

        lblValue = new JLabel("0");
        add(lblValue);

        JButton addButton = new JButton("Please Wait");
        addButton.addActionListener(this);
        addButton.setSize(new Dimension(WIDTH1, HEIGHT1));
        addButton.setPreferredSize(new Dimension(WIDTH1, HEIGHT1));
        addButton.setMinimumSize(new Dimension(WIDTH1, HEIGHT1));
        addButton.setMaximumSize(new Dimension(WIDTH1, HEIGHT1));
        add(addButton);

        JButton resetButton = new JButton("Restart");
        resetButton.setSize(new Dimension(WIDTH2, HEIGHT2));
        resetButton.setPreferredSize(new Dimension(WIDTH2, HEIGHT2));
        resetButton.setMinimumSize(new Dimension(WIDTH2, HEIGHT2));
        resetButton.setMaximumSize(new Dimension(WIDTH2, HEIGHT2));

        JLabel label = new JLabel("Starting Soon");
        setLayout(new GridBagLayout());
        add(label);

        Timer timer = new Timer(1000, new ActionListener() {

          public void actionPerformed(ActionEvent e) {
            count--;
            if (count >= 0) {
              label.setText(Integer.toString(count));
            }
            else {
              ((Timer) (e.getSource())).stop();
              remove(addButton);
              label.setText("");
              lblValue.setText("You clicked " + clicks / 5d + " clicks per second.");
              add(resetButton);
            }
            if (count == 5) {
                addButton.setText("Click Here");
            }
          }

        });
        timer.setInitialDelay(3000);
        timer.start();

    }
    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand( );
        if (actionCommand.equals("Click Here"))
        {
            lblValue.setText(Integer.toString(clicks += 1));
        }
    }
}
英文:

I have added a button, that is initially "Please Wait" and changes to "Click Here" as the timer starts. I need to make it so that if the button is clicked, whilst the text is "Please Wait", it starts the timer, rather than having the timer start itself after the 3000ms.

I also am wondering how I could make the restart button, actually restart the test.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
public class Main extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
//Width and Height of the JFrame
public static final int WIDTH = 550;
public static final int HEIGHT = 550;
//Width and Height of the Add Button
public static final int WIDTH1 = 450;
public static final int HEIGHT1 = 450;
//Width and Height of Restart Button
public static final int WIDTH2 = 125;
public static final int HEIGHT2 = 25;
//Adding the 3 main components
//This is the label that counts the clicks
private JLabel lblValue;
//This is the integer that counts the clicks
private int clicks = 0;
//This is the timer
private int count = 6;
public static void main(String[] args)
{
// This creates two instances of Main,
// which creates two different windows.
Main counter1 = new Main( );
counter1.setVisible(true);
Main counter2 = new Main( );
counter2.setVisible(true);
}
public Main( )
{
//Title that appears at the top of the page
setTitle("CPS Test");
//Close when the close button is pressed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting size of the frame
setSize(WIDTH, HEIGHT);
setMaximumSize(new Dimension(WIDTH, HEIGHT));
setMinimumSize(new Dimension(WIDTH, HEIGHT));
setLayout(new FlowLayout( ));
// This is the label for the amount of clicks
lblValue = new JLabel("0");
//Adding the counter onto the screen
add(lblValue);
//This is the button that adds 1 every time clicked
JButton addButton = new JButton("Please Wait");
addButton.addActionListener(this);
//Setting size for button
addButton.setSize(new Dimension(WIDTH1, HEIGHT1));
addButton.setPreferredSize(new Dimension(WIDTH1, HEIGHT1));
addButton.setMinimumSize(new Dimension(WIDTH1, HEIGHT1));
addButton.setMaximumSize(new Dimension(WIDTH1, HEIGHT1));
//Adding button onto screen
add(addButton);
JButton resetButton = new JButton("Restart");
//Setting size for button
resetButton.setSize(new Dimension(WIDTH2, HEIGHT2));
resetButton.setPreferredSize(new Dimension(WIDTH2, HEIGHT2));
resetButton.setMinimumSize(new Dimension(WIDTH2, HEIGHT2));
resetButton.setMaximumSize(new Dimension(WIDTH2, HEIGHT2));
//Adds the label for the timer. This changes after 1000 milliseconds to 1, and then counts every second
JLabel label = new JLabel("Starting Soon");
setLayout(new GridBagLayout());
//Adding timer onto the screen
add(label);
//Delay in milliseconds between number adding
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Add 1 to count every interval of 1000 milliseconds
count--;
//Timer keeps ticking till this number is achieved
if (count >= 0) {
label.setText(Integer.toString(count));
}
//Will stop timer, remove the click button and will calculate how many clicks you got per second
else {
((Timer) (e.getSource())).stop();
remove(addButton);
label.setText("");
lblValue.setText("You clicked " + clicks / 5d + " clicks per second.");
add(resetButton);
}
//Will change text from "Please Wait" to "Click Here" after timer delay has finished
if (count == 5) {
addButton.setText("Click Here");
}
}
});
//Timer wont start for 3000 milliseconds
timer.setInitialDelay(3000);
//Start Timer
timer.start();
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand( );
//This will only work whilst the text is "Click Here". Wont work for 1000 milliseconds as the text is "Please Wait"
if (actionCommand.equals("Click Here"))
{
//Adds 1 to the click counter ever time it is clicked
lblValue.setText(Integer.toString(clicks += 1));
}
}
}```
</details>
# 答案1
**得分**: 4
根据[Andrew Thompson][1]的指示,你需要完成四个步骤来解决这个问题。
**1.) 计时器应该是类的全局变量**
这一步很重要,否则对象无法从我们即将创建的ActionListeners内部访问。
```java
import javax.swing.Timer;
public class Test {
private Timer timer;
public Test() {
}
}

2.) 在构造函数中创建计时器元素

在构造函数中,我们将初始化计时器,但是重要的是 - 我们暂时不会启动它。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //计时器应该做什么?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
  }
}

3.) 在开始按钮的ActionListener中启动计时器

在这一步中,我们通过按下按钮来启动计时器的功能。为此,我们使用了一个ActionListener和计时器的start()方法。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //计时器应该做什么?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton("开始");
    
    //在这里添加功能
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("计时器已启动!");
          timer.start();
        } 
      }
    }); 
  }
}

4.) 在停止按钮的ActionListener中停止计时器

这基本上是相反的过程。我们将创建另一个按钮,以添加停止计时器功能。为此,我们再次使用ActionListener和计时器的stop()方法。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //计时器应该做什么?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton("开始");
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("计时器已启动!");
          timer.start();
        } 
      }
    });
    
    //在这里添加功能
    JButton stop = new JButton("停止");
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println("计时器已停止!");
          timer.stop();
        } 
      }
    });
  }
}

最后一步:创建其余的GUI

这对于回答你的问题不再必要,但我想提供一个最小的工作示例。为此,我使用了SwingUtilities.invokeLater()。关于这是在做什么以及为什么应该使用它的更多信息,请参阅这个问题

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //计时器应该做什么?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton("开始");
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("计时器已启动!");
          timer.start();
        } 
      }
    });
    
    JButton stop = new JButton("停止");
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println("计时器已停止!");
          timer.stop();
        } 
      }
    });
    
    //最小工作示例
    JFrame frame = new JFrame("计时器");
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(start);
    panel.add(stop);
    frame.add(panel);
    
    frame.setSize(300,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  
  public static void main(String[] args) {
    SwingUtilities.invokeLater(Test::new);
  }
}
英文:

As Andrew Thompson pointed out, you will have to go through four steps to solve this problem.

1.) The Timer should be a global variable of the class

This step is important because otherwise the object wouldn't be accessible from inside the ActionListeners we are going to create.

import javax.swing.Timer;

public class Test {
  private Timer timer;
  
  public Test() {

  }
}

2.) Create the timer-element in the constructor

In the constructor, we are now going to initialize the timer, but - and this is important - we are not going to to start it yet.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
  }
}

3.) Start the timer in the ActionListener of the start-button

In this step we are adding the functionality to start the timer by pressing a button. For this purpose we are using an ActionListener and the start()-method of the timer.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton(&quot;Start&quot;);
    
    //Here the functionality is added
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println(&quot;Timer started!&quot;);
          timer.start();
        } 
      }
    }); 
  }
}

4.) Stop the timer in the ActionListener of the stop-button

This is basically the other way around. We are going to create another button to add the the functionality to stop the timer. For this purpose we are going to use an ActionListener again and the stop()-method of the timer.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton(&quot;Start&quot;);
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println(&quot;Timer started!&quot;);
          timer.start();
        } 
      }
    });
    
    //Functionality is added here
    JButton stop = new JButton(&quot;stop&quot;);
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println(&quot;Timer stopped!&quot;);
          timer.stop();
        } 
      }
    });
  }
}

Final step: Create the rest of the GUI

This isn't necessary for answering your question anymore, but I wanted to provide a minimal working example. For this, I am using SwingUtilities.invokeLater(). For more information on what this is doing and why you should use it, please see this question.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Test {
  private Timer timer;
  private int count = 0;
  
  public Test() {
    ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000, taskPerformer);
    
    JButton start = new JButton(&quot;Start&quot;);
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println(&quot;Timer started!&quot;);
          timer.start();
        } 
      }
    });
    
    JButton stop = new JButton(&quot;stop&quot;);
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println(&quot;Timer stopped!&quot;);
          timer.stop();
        } 
      }
    });
    
    //Minimal working example 
    JFrame frame = new JFrame(&quot;Timer&quot;);
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(start);
    panel.add(stop);
    frame.add(panel);
    
    frame.setSize(300,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  
  public static void main(String[] args) {
    SwingUtilities.invokeLater(Test::new);
  }
}

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

发表评论

匿名网友

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

确定