答案取決於。你只想知道按鈕什麼時候被「點擊」兩次或者什麼時候被「按下」兩次?
它一般不提倡到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