我想在点击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);
}
}
});
如何防止单击事件窃取双击?
答案 0 :(得分:1)
这是一个不完美问题的不完美解决方案。就其本质而言,双击将产生两个鼠标事件,但双击是在相互之间的短时间内发生的任意两次点击。
因此,您可以在第一次点击时插入一个小延迟,如果触发,将会"假设"该事件只需单击一次。
此示例使用设置为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 )一键更改菜单的状态
答案 1 :(得分:0)
if (e.getClickCount() == 2 && !e.isConsumed()) {
e.consume();
...
}