我有一个java swing GUI,其中必须执行双击和单击的特定操作。 我有这个代码
if (e.getClickCount() == 1)
{
// do something on single click
}
if (e.getClickCount() == 2)
{
// do something on double click
}
工作正常。问题是此代码对于鼠标右键和左键单击的行为相同。我不想对双击右键执行任何操作。只想在单击右键时显示弹出菜单。
任何身体都请指导我。感谢
答案 0 :(得分:3)
你必须在你的MouseEvent对象(变量“e”)中检查导致事件的按钮:
if(e.getClickCount() == 2){ // two clicks, ok
if((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){
// clicks are from BUTTON1, aka left click
// double left click, insert code here
}
}
答案 1 :(得分:1)
您可以使用此代码,Double_Click
中选中Swing Timer
,其他选项使用Toolkit
(从未使用过),也许more info here
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ClickListener extends MouseAdapter implements ActionListener {
private final static int clickInterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
private MouseEvent lastEvent;
private Timer timer;
public ClickListener() {
this(clickInterval);
}
public ClickListener(int delay) {
timer = new Timer(delay, this);
}
@Override
public void mouseClicked(MouseEvent e) {
/*if (e.getClickCount() > 2) {
return;
}
lastEvent = e;
if (timer.isRunning()) {
timer.stop();
doubleClick(lastEvent);
} else {
timer.restart();
}*/
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double");
timer.stop();
} else {
timer.restart();
}
}
@Override
public void actionPerformed(ActionEvent e) {
timer.stop();
singleClick(lastEvent);
}
public void singleClick(MouseEvent e) {
}
public void doubleClick(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new JFrame("Double Click Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(new ClickListener() {
@Override
public void singleClick(MouseEvent e) {
System.out.println("single");
}
@Override
public void doubleClick(MouseEvent e) {
System.out.println("double");
}
});
frame.setPreferredSize(new Dimension(200, 200));
frame.pack();
frame.setVisible(true);
}
}