1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.xnap.commons.gui.util;
22
23 import java.awt.Component;
24 import java.awt.Point;
25 import java.awt.event.MouseAdapter;
26 import java.awt.event.MouseEvent;
27 import javax.swing.JMenu;
28 import javax.swing.JPopupMenu;
29 import javax.swing.JTable;
30 import javax.swing.JTree;
31
32 /***
33 * Provides a mouse event listener that displays a popup menu if the user
34 * presses the platform dependent popup button.
35 */
36 public class PopupListener extends MouseAdapter {
37
38 private JPopupMenu popup;
39
40 public PopupListener(JMenu menu)
41 {
42 this(menu.getPopupMenu());
43 }
44
45 public PopupListener(JPopupMenu popup)
46 {
47 this.popup = popup;
48 popup.setBorderPainted(true);
49 }
50
51 public PopupListener()
52 {
53 }
54
55 public void mousePressed(MouseEvent e)
56 {
57 showPopup(e);
58 }
59
60 public void mouseReleased(MouseEvent e)
61 {
62 showPopup(e);
63 }
64
65 private void showPopup(MouseEvent e)
66 {
67 if (e.isPopupTrigger()) {
68 if (!makeSelection(e.getComponent(), e.getPoint(),
69 e.isControlDown())) {
70 return;
71 }
72
73 e.getComponent().requestFocus();
74 showPopup(e.getComponent(), e.getX(), e.getY());
75 }
76 }
77
78 /***
79 * Shows the popup menu.
80 *
81 * @see GUIHelper#showPopupMenu(JPopupMenu, Component, int, int)
82 */
83 protected void showPopup(Component source, int x, int y)
84 {
85 JPopupMenu popupMenu = getPopupMenu();
86 if (popupMenu != null) {
87 GUIHelper.showPopupMenu(popupMenu, source, x, y);
88 }
89 }
90
91 public JPopupMenu getPopupMenu()
92 {
93 return popup;
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 }