单击按钮而不是单独地启动计时器javax.swing

如何解决单击按钮而不是单独地启动计时器javax.swing

添加一个按钮,最初是“请稍候”,并在计时器启动时更改为“单击此处”。我需要这样做,以便如果单击按钮时文本为“ Please Wait”,则它将启动计时器,而不是让计时器在3000毫秒后自行启动。

我还想知道如何设置重新启动按钮,实际上重新启动测试。

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));

        }
    }
}```

解决方法

正如Andrew Thompson所指出的,您将必须经过四个步骤来解决此问题。

1。)Timer应该是该类的全局变量

这一步很重要,因为否则,将无法从我们要创建的ActionListener中访问该对象。

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) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000,taskPerformer);
  }
}

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

在此步骤中,我们添加了通过按按钮启动计时器的功能。为此,我们使用计时器的ActionListenerstart()方法。

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("Start");
    
    //Here the functionality is added
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("Timer started!");
          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) {
        //What should the timer do?
        count++;
        System.out.println(count);
      }
    }; 
    timer = new Timer(1000,taskPerformer);
    
    JButton start = new JButton("Start");
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("Timer started!");
          timer.start();
        } 
      }
    });
    
    //Functionality is added here
    JButton stop = new JButton("stop");
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println("Timer stopped!");
          timer.stop();
        } 
      }
    });
  }
}

最后一步:创建其余的GUI

这不再是回答您的问题所必需的,但是我想提供一个最小的工作示例。为此,我正在使用SwingUtilities.invokeLater()。有关此操作的详细信息以及为什么要使用它,请参阅this问题。

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("Start");
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(!timer.isRunning()) {
          System.out.println("Timer started!");
          timer.start();
        } 
      }
    });
    
    JButton stop = new JButton("stop");
    stop.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        if(timer.isRunning()) {
          count = 0;
          System.out.println("Timer stopped!");
          timer.stop();
        } 
      }
    });
    
    //Minimal working example 
    JFrame frame = new JFrame("Timer");
    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);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?