1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.lf5.viewer;
18
19 import javax.swing.*;
20 import javax.swing.table.TableModel;
21 import java.awt.*;
22
23 /***
24 * Provides methods to accomplish common yet non-trivial tasks
25 * with Swing. Obvious implementations of these methods have been
26 * tried and failed.
27 *
28 * @author Richard Wan
29 */
30
31
32
33 public class LF5SwingUtils {
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 /***
55 * Selects a the specified row in the specified JTable and scrolls
56 * the specified JScrollpane to the newly selected row. More importantly,
57 * the call to repaint() delayed long enough to have the table
58 * properly paint the newly selected row which may be offscre
59 * @param table should belong to the specified JScrollPane
60 */
61 public static void selectRow(int row, JTable table, JScrollPane pane) {
62 if (table == null || pane == null) {
63 return;
64 }
65 if (contains(row, table.getModel()) == false) {
66 return;
67 }
68 moveAdjustable(row * table.getRowHeight(), pane.getVerticalScrollBar());
69 selectRow(row, table.getSelectionModel());
70
71
72
73 repaintLater(table);
74 }
75
76 /***
77 * Makes the specified Adjustable track if the view area expands and
78 * the specified Adjustable is located near the of the view.
79 */
80 public static void makeScrollBarTrack(Adjustable scrollBar) {
81 if (scrollBar == null) {
82 return;
83 }
84 scrollBar.addAdjustmentListener(new TrackingAdjustmentListener());
85 }
86
87 /***
88 * Makes the vertical scroll bar of the specified JScrollPane
89 * track if the view expands (e.g. if rows are added to an underlying
90 * table).
91 */
92 public static void makeVerticalScrollBarTrack(JScrollPane pane) {
93 if (pane == null) {
94 return;
95 }
96 makeScrollBarTrack(pane.getVerticalScrollBar());
97 }
98
99
100
101
102 protected static boolean contains(int row, TableModel model) {
103 if (model == null) {
104 return false;
105 }
106 if (row < 0) {
107 return false;
108 }
109 if (row >= model.getRowCount()) {
110 return false;
111 }
112 return true;
113 }
114
115 protected static void selectRow(int row, ListSelectionModel model) {
116 if (model == null) {
117 return;
118 }
119 model.setSelectionInterval(row, row);
120 }
121
122 protected static void moveAdjustable(int location, Adjustable scrollBar) {
123 if (scrollBar == null) {
124 return;
125 }
126 scrollBar.setValue(location);
127 }
128
129 /***
130 * Work around for JTable/viewport bug.
131 * @link http://developer.java.sun.com/developer/bugParade/bugs/4205145.html
132 */
133 protected static void repaintLater(final JComponent component) {
134 SwingUtilities.invokeLater(new Runnable() {
135 public void run() {
136 component.repaint();
137 }
138 });
139 }
140
141
142
143
144
145
146
147 }
148