1

我有一个 java swing GUI,其中必须在双击和单击时执行特定操作。我有这个代码

 if (e.getClickCount() == 1)
    {
    // do something on single click
    }
    if (e.getClickCount() == 2)
    {
    // do something on double click
    }

它工作正常。问题是此代码对于鼠标右键和左键单击的行为相同。我不想在双击右键时执行任何操作。只想在单击鼠标右键时显示​​弹出菜单。

任何机构请指导我。谢谢

4

2 回答 2

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      
    }
}
于 2012-04-16T13:28:57.597 回答
1

你可以使用这个代码,Double_Click里面检查的地方Swing Timer,另一个选项是使用Toolkit(从未使用过),也许更多信息在这里

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);
    }
}
于 2012-04-16T13:31:17.087 回答