Count how many times a JButton is pressed?

2020-04-22 05:23发布

问题:

In the action performed code in a JAVA GUI, how would I count how many times a button is pressed, and do something different for each press of the button?

  private class Listener implements ActionListener
  {
     public void actionPerformed (ActionEvent e)
     {

       HOW WOULD I COUNT HOW MANY TIMES THIS BUTTON HAS BEEN PRESSED?

     }

Thanks!!!

回答1:

Create a class variable and then increment the variable in the method.

private class Listener implements ActionListener   
{      
    private int clicked;

    public void actionPerformed (ActionEvent e)
    {
         clicked++
    }
}

You can then create a method to access the variable.



回答2:

You can have a field in the Listener class and increment it every time the button is pressed and then have a switch to select the action to perform depending on the value of your variable.

private class Listener implements ActionListener   
{      
    private int clicks;

    public void actionPerformed (ActionEvent e)
    {
        clicks++;
        switch (clicks){
            case '1':
                // Do operation 1
                break;
            case '2':
                // Do operation 2
                break;
        }
    }
}


回答3:

You have declared clicks as int, therefore, case statement needs int value not the char.

Corrected version:

private class Listener implements ActionListener   
{      
    private int clicks;

    public void actionPerformed (ActionEvent e)
    {
        clicks++;
        switch (clicks){
            case 1:
                // Do operation 1
                break;
            case 2:
                // Do operation 2
                break;
        }
    }
}


回答4:

Just use e.getClickCount in your MouseEvent