答案取决于。你只想知道按钮什么时候被“点击”两次或者什么时候被“按下”两次?
它一般不提倡到MouseListener
附加到一个按钮,该按钮可以以多种方式被触发,包括编程
你所需要的是能够做到的,是不是只算次数actionPerformed
被调用,但也知道点击之间的时间。
您可以记录最后一次点击时间,并将其与当前时间进行比较,并以此方式进行确定,或者您可以简单地使用javax.swing.Timer
这将为您做。
下面的例子还检查,看是否ActionEvent
的最后一个来源是一样的电流源,如果它不是计数器复位......
这也使得鼠标点击,按键和方案触发器...
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");
}
}
}
}
答案取决于OP是否只想知道鼠标点击或想要继续支持正常的交互(如[enter]或[space]) – MadProgrammer