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;
}
}
}
Just use e.getClickCount
in your MouseEvent