最后一个按钮单击+ n秒后重置计数器

时间:2016-03-19 14:39:06

标签: java swing jbutton

我有一个简单的代码来计算按钮点击次数

btn1.addActionListener(new ActionListener() {
    private int counter = 0;
    public void actionPerformed(ActionEvent e) {
        counter++;
        textOutput.setText(String.valueOf(counter));
    }
}

我希望在最后一次按钮点击后经过n个时间(即1秒)后实现计数器重置功能。

感谢您的任何想法。

2 个答案:

答案 0 :(得分:3)

我会让你为此编写自己的代码,但步骤很简单:

  • 创建一个Swing Timer,在其ActionListener中,只需将count重置为0,并在textOutput组件中显示。
  • 在Timer的构造函数中,传入timer delay int - 无论你想在重置计数之前给用户多长时间,以及上面的ActionListener。
  • 通过调用setRepeats(false)使计时器不可重复。
  • 在按钮的ActionListener中,只需在设置textOutput文本后调用计数器上的restart()
  • 请注意,您不能在JButton的ActionListener中声明您的计数器字段,因为这会限制其范围太多,除非按钮&# 39; ActionListener还有这个值的getter和setter字段,Timer的ActionListener可以调用它。

我没有显示代码,但是由于其他人做了,我有点不得不承担责任。请参阅解释代码中的注释。

Key是Timer的ActionListener。它只是重置了计数器

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            setCounter(0);  // this is all the timer does
        }
    }

请注意,在我的代码中,setCounter(int counter)方法设置了int计数器值并将其显示在JLabel 中:

// method that sets counter value **and** displays value in JLabel
public void setCounter(int counter) {
    this.counter = counter;
    counterLabel.setText(String.valueOf(counter));
}

JButton的ActionListener实际上是一个AbstractAction类,有点像ActionListener"类固醇"。它执行ActionListener所做的所有操作,并设置按钮的文本并为按钮提供助记键,并且还可以执行更多操作。它所做的就是推进计数器并在计时器上调用restart(),这就是它:

    // ActionListener (and more) for the button
    private class ButtonPressAction extends AbstractAction {
        public ButtonPressAction(String name, int mnemonic) {
            super(name);  // text to show in button
            putValue(MNEMONIC_KEY, mnemonic);  // alt-key mnemonic key for button
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            setCounter(counter + 1);  // re-sets the counter and displays it
            timer.restart();   // re-sets and runs the timer
        }
    }

整个计划:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;    
import javax.swing.*;

@SuppressWarnings("serial")
public class ResetCounter extends JPanel {
    private static final int TIMER_DELAY = 1000; // 1 second delay
    private int counter = 0;  // our counter field
    private JLabel counterLabel = new JLabel("   0   ", SwingConstants.CENTER); // label to display counter value
    private JButton button = new JButton(new ButtonPressAction("Click Me", KeyEvent.VK_C));  // our button with its AbstractAction
    private Timer timer = new Timer(TIMER_DELAY, new TimerListener()); // the Swing Timer loaded with its delay and ActionListener

    public ResetCounter() {
        // make sure timer does not repeat
        timer.setRepeats(false);

        // create JPanel to hold JLabels that give counter information
        JPanel topPanel = new JPanel();
        topPanel.add(new JLabel("Count:"));
        topPanel.add(counterLabel);

        // JPanel to hold the button
        JPanel midPanel = new JPanel();
        midPanel.add(button);
        int ebGap = 15; // make mid panel bigger
        midPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));

        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(midPanel, BorderLayout.CENTER);
    }

    // method that sets counter value **and** displays value in JLabel
    public void setCounter(int counter) {
        this.counter = counter;
        counterLabel.setText(String.valueOf(counter));
    }

    // ActionListener (and more) for the button
    private class ButtonPressAction extends AbstractAction {
        public ButtonPressAction(String name, int mnemonic) {
            super(name);  // text to show in button
            putValue(MNEMONIC_KEY, mnemonic);  // alt-key mnemonic key for button
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            setCounter(counter + 1);  // re-sets the counter and displays it
            timer.restart();   // re-sets and runs the timer
        }
    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            setCounter(0);  // this is all the timer does
        }
    }

    private static void createAndShowGui() {
        ResetCounter mainPanel = new ResetCounter();

        JFrame frame = new JFrame("ResetCounter");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }

}

答案 1 :(得分:1)

  

在最后一个按钮单击+ n秒后重置计数器

如果你想自己跟踪时间,你可以使用Swing.Timer:

enter image description here

在演示中,点击次数将每5秒重置为0。

我创建了计时器到#34; tick"以大约每1秒的间隔。只有在单击按钮时才会触发计时器,并且经过的时间(variable int time)将开始计时。当经过的时间等于延迟(variable int delayInSeconds)时,它将重置点击次数(variable int clicks)的计数并停止计时器。

当用户再次点击按钮时,整个过程将重复。

class MainPanel extends JPanel
{
    private Timer timer;
    private JButton btn;
    private JLabel lblTime, lblClicks;  
    private int clicks, time, delayInSeconds;

    public MainPanel(){
        setPreferredSize(new Dimension(100, 100));
        initComponents();
        addComponents();    
    }

    private void initComponents(){
        time = 0;           //elapsed time in seconds
        clicks = 0;         //clicks accumulated
        delayInSeconds = 5; //delay to reset click count

        btn = new JButton("Click me");
        btn.addActionListener(new ButtonHandler());
        lblTime = new JLabel("Elapsed time: " + time);
        lblClicks = new JLabel("Num of Clicks:" + clicks);          
        timer = new Timer(1000, new ActionListener(){  
            @Override
            public void actionPerformed(ActionEvent e){             
                time ++;                
                if(time >= delayInSeconds){
                    clicks = 0;
                    time = 0;                   
                    timer.stop();                   
                }
                updateDisplay();                
            }               
        });                     
    }

    private void addComponents(){
        add(lblTime);
        add(lblClicks);
        add(btn);                   
    }

    private void updateDisplay(){
        lblClicks.setText("Num of Clicks: " + clicks);
        lblTime.setText("Elapsed time: " + time);
    }

    private class ButtonHandler implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            clicks ++;  //gather clicks
            time = 0;   //reset time count
            timer.start();
            updateDisplay();
        }
    }
}

用于驱动代码的跑步者类:

class ClickCounter{
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                JFrame frame = new JFrame("Click Counter");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new MainPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);             
            }
        });
    }
}

注意:如果您打算使用它来检测双击或三击。 Swing已经为您实现了此功能。您可以使用e.getClickCount()

@Override
public void mouseClicked(MouseEvent e){
    if(e.getClickCount() == 2)      
        System.out.println(“double click”);
}