1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.gui.event;
21
22 import java.awt.Component;
23 import java.awt.Point;
24 import java.awt.event.MouseAdapter;
25 import java.awt.event.MouseEvent;
26
27 import javax.swing.JMenu;
28 import javax.swing.JPopupMenu;
29 import javax.swing.JTable;
30 import javax.swing.JTree;
31
32 import org.xnap.gui.util.GUIHelper;
33
34 /***
35 * Provides a mouse event listener that displays a popup menu if the user
36 * presses the platform dependent popup button.
37 */
38 public class PopupListener extends MouseAdapter {
39
40
41
42
43
44 private JPopupMenu popup;
45 private boolean firstTime;
46
47
48
49 public PopupListener(JMenu menu)
50 {
51 this(menu.getPopupMenu());
52 }
53
54 public PopupListener(JPopupMenu popup)
55 {
56 this.popup = popup;
57 popup.setBorderPainted(true);
58 }
59
60
61
62
63 public void mousePressed(MouseEvent e)
64 {
65 showPopup(e);
66 }
67
68 public void mouseReleased(MouseEvent e)
69 {
70 showPopup(e);
71 }
72
73 private void showPopup(MouseEvent e)
74 {
75 if (e.isPopupTrigger()) {
76 if (!makeSelection(e.getComponent(), e.getPoint(),
77 e.isControlDown())) {
78 return;
79 }
80
81 e.getComponent().requestFocus();
82 showPopup(e.getComponent(), e.getX(), e.getY());
83 }
84 }
85
86 /***
87 * Shows the popup menu.
88 *
89 * @see GUIHelper#showPopupMenu(JPopupMenu, Component, int, int)
90 */
91 protected void showPopup(Component source, int x, int y)
92 {
93 GUIHelper.showPopupMenu(popup, source, x, y);
94 }
95
96 private boolean makeSelection(Object parent, Point point, boolean multiple)
97 {
98 if (parent instanceof JTable) {
99 JTable table = (JTable)parent;
100 int row = table.rowAtPoint(point);
101
102 if(row == -1)
103 return false;
104
105
106 int[] rows = table.getSelectedRows();
107 boolean selectRow = true;
108 for (int i = 0; i < rows.length; i++) {
109 if (rows[i] == row)
110 selectRow = false;
111 }
112
113 if (selectRow) {
114 table.getSelectionModel().setSelectionInterval(row, row);
115 }
116
117 }
118 else if (parent instanceof JTree) {
119 JTree tree = (JTree)parent;
120 int row = tree.getClosestRowForLocation(point.x, point.y);
121
122 if (row == -1)
123 return false;
124
125 if (multiple)
126 tree.addSelectionRow(row);
127 else
128 tree.setSelectionRow(row);
129 }
130
131 return true;
132 }
133
134 }