TrayIconがシングルまたはダブルクリックされたかを区別する
Total: 590, Today: 1, Yesterday: 4
Posted by aterai at
Last-modified:
Summary
TrayIconがマウスでシングルクリックされたか、ダブルクリックされたかを区別して開くウィンドウを切り替えます。
Screenshot

Advertisement
Source Code Examples
JDialog tmp = new JDialog();
tmp.setUndecorated(true);
tmp.setAlwaysOnTop(true);
Point loc = new Point();
Image image = makeDefaultTrayImage();
TrayIcon icon = new TrayIcon(image, "TRAY", null);
icon.addMouseListener(new TrayIconPopupMenuHandler(popup, tmp));
icon.addMouseListener(new MouseAdapter() {
private final Timer timer = new Timer(500, e -> {
((Timer) e.getSource()).stop();
openLookAndFeelBox(lnf, tmp, loc);
});
@Override public void mousePressed(MouseEvent e) {
loc.setLocation(e.getPoint());
if (SwingUtilities.isLeftMouseButton(e)) {
timer.setDelay(500);
timer.setRepeats(false);
timer.start();
}
}
@Override public void mouseClicked(MouseEvent e) {
boolean isDoubleClick = e.getClickCount() >= 2;
if (SwingUtilities.isLeftMouseButton(e) && isDoubleClick) {
timer.stop();
lnf.setVisible(false);
frame.setVisible(true);
}
}
});
try {
SystemTray.getSystemTray().add(icon);
} catch (AWTException ex) {
throw new IllegalStateException(ex);
}
View in GitHub: Java, KotlinDescription
TrayIconを右クリックした場合に開くポップアップメニューとしてjava.awt.PopupMenuではなくjavax.swing.JPopupMenuを使用するよう設定JMenuItemのタイトルに<table>タグを使用してmnemonicsやacceleratorsではなくマウスクリックの種類をヘルプ表示JPopupMenu表示用のMouseListenerとは別にマウス左ボタンクリック用のMouseListenerをTrayIconに追加- TrayIconのダブルクリック
MouseListener#mousePressed(...)で繰り返し無効(Timer#setRepeats(false))に設定したTimerをスタート- 指定時間後にシングルクリック向けのウィンドウ(
JPopupMenuで作成)を開く
- 指定時間後にシングルクリック向けのウィンドウ(
MouseListener#mouseClicked(...)ではダブルクリックのみ検知してシングルクリック用のTimerをストップし、ダブルクリック向けのウィンドウ(JFrame)を開く- シングルクリックの場合ここでは何も実行しない