The answer depends. Do you only want to know when the button is "clicked" twice or when it is "pressed" twice?
It's generally discouraged to attach a MouseListener
to a button, as the button can be triggered in a variety of ways, including programmatically
What you need to be able to do, is not only count the number of times actionPerformed
is called, but also know the time between the clicks.
You could record the last click time and compare that with the current time and make determinations that way, or you could simply use a javax.swing.Timer
which will do it for you.
The following example also checks to see if the last source of the ActionEvent
is the same as the current source and resets the counter if it's not...
This also allows for mouse clicks, key presses and programmatic triggers...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TimerButton {
public static void main(String[] args) {
new TimerButton();
}
public TimerButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JButton btn = new JButton("Testing");
btn.addActionListener(new ActionHandler());
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ActionHandler implements ActionListener {
private Timer timer;
private int count;
private ActionEvent lastEvent;
public ActionHandler() {
timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Tick " + count);
if (count == 2) {
doubleActionPerformed();
}
count = 0;
}
});
timer.setRepeats(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if (lastEvent != null && lastEvent.getSource() != e.getSource()) {
System.out.println("Reset");
count = 0;
}
lastEvent = e;
((JButton)e.getSource()).setText("Testing");
count++;
System.out.println(count);
timer.restart();
}
protected void doubleActionPerformed() {
Object source = lastEvent.getSource();
if (source instanceof JButton) {
((JButton)source).setText("Double tapped");
}
}
}
}