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.event.ActionEvent;
25 import java.awt.event.ActionListener;
26 import java.awt.event.MouseAdapter;
27 import java.awt.event.MouseEvent;
28 import java.util.ArrayList;
29 import java.util.List;
30 import javax.swing.JList;
31 import javax.swing.JTable;
32 import javax.swing.JTree;
33
34 /***
35 * Convenience class for a double click listener in a table. Use it like this:
36 *
37 * <pre>
38 * table.addMouseListener(new DoubleClickListener(action));
39 * </pre>
40 */
41 public class DoubleClickListener extends MouseAdapter {
42
43 public static final int DOUBLE_CLICK_ID = 0;
44
45 private String actionCommand;
46 private List<ActionListener> listeners = new ArrayList<ActionListener>();
47
48 public DoubleClickListener()
49 {
50 }
51
52 public DoubleClickListener(ActionListener listener)
53 {
54 addActionListener(listener);
55 }
56
57 public void addActionListener(ActionListener listener)
58 {
59 listeners.add(listener);
60 }
61
62 public String getActionCommand()
63 {
64 return actionCommand;
65 }
66
67 public void mousePressed(MouseEvent e)
68 {
69 Component component = e.getComponent();
70 if (e.getClickCount() == 2) {
71 int row = 0;
72 if (component instanceof JTable) {
73 row = ((JTable)component).rowAtPoint(e.getPoint());
74
75 }
76 else if (component instanceof JList) {
77 row = ((JList)component).locationToIndex(e.getPoint());
78 }
79 else if (component instanceof JTree) {
80 row = ((JTree)component).getRowForLocation(e.getX(), e.getY());
81 }
82
83 if (row != -1) {
84 ActionListener[] array = listeners.toArray(new ActionListener[0]);
85 if (array.length > 0) {
86 ActionEvent event = new ActionEvent(component, DOUBLE_CLICK_ID, getActionCommand());
87 for (int i = array.length - 1; i >= 0; i--) {
88 array[i].actionPerformed(event);
89 }
90 }
91 }
92 }
93 }
94
95 public void removeActionListener(ActionListener listener)
96 {
97 listeners.remove(listener);
98 }
99
100 public void setActionCommand(String actionCommand)
101 {
102 this.actionCommand = actionCommand;
103 }
104
105 }
106