简体   繁体   中英

Count how many times a JButton is pressed?

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!!!

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.

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

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

只需在MouseEvent中使用e.getClickCount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM