gpt4 book ai didi

Java 托盘图标 : addMouseListener -> distinguish between single click and double click?

转载 作者:行者123 更新时间:2023-11-30 11:04:46 28 4
gpt4 key购买 nike

我想在点击 TrayIcon 时显示警告,并在双击它时显示主窗口。我在捕获双击事件时遇到问题:每次双击时,都会触发两个单击事件。

我正在使用以下代码:

        trayIcon.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1 && e.getButton() == 1) {
trayIcon.displayMessage(...);
} else if (e.getClickCount() == 2 && e.getButton() == 1) {
frame.setVisible(true);
}
}
});

如何防止单击事件窃取双击事件?

最佳答案

这是对不完美问题的不完美解决方案。从本质上讲,双击会产生两个鼠标事件,但双击是在短时间内发生的任意两次单击。

因此,您可以在第一次点击时插入一个小的延迟,如果触发,将“假定”该事件只是一次点击。

此示例使用设置为 300 毫秒的 Swing Timer(您可以尝试 250-275,但我发现 300 刚刚好)。当它检测到第一次点击时,它启动定时器,如果它检测到第二次点击,它停止定时器,否则允许定时器在 300 毫秒延迟后执行,假设是双击...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class JavaApplication314 {

public static void main(String[] args) {
new JavaApplication314();
}

public JavaApplication314() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JLabel label;

public TestPane() {
addMouseListener(new MouseHandler());
label = new JLabel("...");
setLayout(new GridBagLayout());
add(label);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

protected void doOneClick() {
label.setText("One Click");
}

protected void doTwoClicks() {
label.setText("Two Clicks");
}

public class MouseHandler extends MouseAdapter {

private Timer oneClickTimer;

public MouseHandler() {
oneClickTimer = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doOneClick();
}
});
oneClickTimer.setRepeats(false);
}

@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
oneClickTimer.stop();
doTwoClicks();
} else if (e.getClickCount() == 1) {
oneClickTimer.restart();
}
}



}

}

}

另一种选择可能是使用元键(如 Alt)通过单击更改菜单的状态

关于Java 托盘图标 : addMouseListener -> distinguish between single click and double click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891672/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com