1

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

4 Answers 4

5

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.

1
  • Thanks mate! I quickly realized this was a stupid question after I asked it. I should have spent some more time thinking about it. I really appreciate your help! Apr 9, 2011 at 2:25
1

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;
        }
    }
}
2
  • i assume you mean a field in the class, not a global variable. Apr 9, 2011 at 2:19
  • Yeah, sorry. Too much programming in C for the past 5 days.
    – Sadiq
    Apr 9, 2011 at 2:20
0

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

Just use e.getClickCount in your MouseEvent

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.