View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2017 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.gui;
21  
22  import java.awt.Component;
23  import java.awt.Dimension;
24  import java.awt.FontMetrics;
25  import java.awt.event.ActionEvent;
26  import java.awt.event.MouseAdapter;
27  import java.awt.event.MouseEvent;
28  import java.util.EventObject;
29  import java.util.List;
30  
31  import javax.swing.AbstractAction;
32  import javax.swing.Action;
33  import javax.swing.JTable;
34  import javax.swing.JTextArea;
35  import javax.swing.JTree;
36  import javax.swing.KeyStroke;
37  import javax.swing.LookAndFeel;
38  import javax.swing.table.TableCellEditor;
39  import javax.swing.tree.TreePath;
40  
41  import com.google.common.collect.ImmutableList;
42  
43  /**
44   * This example shows how to create a simple TreeTable component,
45   * by using a JTree as a renderer (and editor) for the cells in a
46   * particular column in the JTable.
47   *
48   * <a href=
49   * "https://docs.oracle.com/cd/E48246_01/apirefs.1111/e13403/oracle/ide/controls/TreeTableModel.html">
50   * Original&nbsp;Source&nbsp;Location</a>
51   *
52   * @author Philip Milne
53   * @author Scott Violet
54   * @author Lars K├╝hne
55   * @noinspection ThisEscapedInObjectConstruction
56   */
57  public class TreeTable extends JTable {
58      private static final long serialVersionUID = -8493693409423365387L;
59      /** A subclass of JTree. */
60      private final TreeTableCellRenderer tree;
61      /** JTextArea editor. */
62      private JTextArea editor;
63      /** Line position map. */
64      private List<Integer> linePositionMap;
65  
66      /**
67       * Creates TreeTable base on TreeTableModel.
68       * @param treeTableModel Tree table model
69       */
70      public TreeTable(ParseTreeTableModel treeTableModel) {
71  
72          // Create the tree. It will be used as a renderer and editor.
73          tree = new TreeTableCellRenderer(this, treeTableModel);
74  
75          // Install a tableModel representing the visible rows in the tree.
76          setModel(new TreeTableModelAdapter(treeTableModel, tree));
77  
78          // Force the JTable and JTree to share their row selection models.
79          final ListToTreeSelectionModelWrapper selectionWrapper = new
80                  ListToTreeSelectionModelWrapper(this);
81          tree.setSelectionModel(selectionWrapper);
82          setSelectionModel(selectionWrapper.getListSelectionModel());
83  
84          // Install the tree editor renderer and editor.
85          setDefaultRenderer(ParseTreeTableModel.class, tree);
86          setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor());
87  
88          // No grid.
89          setShowGrid(false);
90  
91          // No intercell spacing
92          setIntercellSpacing(new Dimension(0, 0));
93  
94          // And update the height of the trees row to match that of
95          // the table.
96          if (tree.getRowHeight() < 1) {
97              // Metal looks better like this.
98              setRowHeight(getRowHeight());
99          }
100 
101         setColumnsInitialWidth();
102 
103         final Action expand = new AbstractAction() {
104             private static final long serialVersionUID = -5859674518660156121L;
105 
106             @Override
107             public void actionPerformed(ActionEvent event) {
108                 expandSelectedNode();
109             }
110         };
111         final KeyStroke stroke = KeyStroke.getKeyStroke("ENTER");
112         final String command = "expand/collapse";
113         getInputMap().put(stroke, command);
114         getActionMap().put(command, expand);
115 
116         addMouseListener(new MouseAdapter() {
117             @Override
118             public void mouseClicked(MouseEvent event) {
119                 if (event.getClickCount() == 2) {
120                     expandSelectedNode();
121                 }
122             }
123         });
124     }
125 
126     /**
127      * Do expansion of a tree node.
128      */
129     private void expandSelectedNode() {
130         final TreePath selected = tree.getSelectionPath();
131         makeCodeSelection();
132 
133         if (tree.isExpanded(selected)) {
134             tree.collapsePath(selected);
135         }
136         else {
137             tree.expandPath(selected);
138         }
139         tree.setSelectionPath(selected);
140     }
141 
142     /**
143      * Make selection of code in a text area.
144      */
145     private void makeCodeSelection() {
146         new CodeSelector(tree.getLastSelectedPathComponent(), editor, linePositionMap).select();
147     }
148 
149     /**
150      * Set initial value of width for columns in table.
151      */
152     private void setColumnsInitialWidth() {
153         final FontMetrics fontMetrics = getFontMetrics(getFont());
154         // Six character string to contain "Column" column.
155         final int widthOfSixCharacterString = fontMetrics.stringWidth("XXXXXX");
156         // Padding must be added to width for columns to make them fully
157         // visible in table header.
158         final int padding = 10;
159         final int widthOfColumnContainingSixCharacterString =
160                 widthOfSixCharacterString + padding;
161         getColumn("Line").setMaxWidth(widthOfColumnContainingSixCharacterString);
162         getColumn("Column").setMaxWidth(widthOfColumnContainingSixCharacterString);
163         final int preferredTreeColumnWidth =
164                 Math.toIntExact(Math.round(getPreferredSize().getWidth() * 0.6));
165         getColumn("Tree").setPreferredWidth(preferredTreeColumnWidth);
166         // Twenty eight character string to contain "Type" column
167         final int widthOfTwentyEightCharacterString =
168                 fontMetrics.stringWidth("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
169         final int preferredTypeColumnWidth = widthOfTwentyEightCharacterString + padding;
170         getColumn("Type").setPreferredWidth(preferredTypeColumnWidth);
171     }
172 
173     /**
174      * Overridden to message super and forward the method to the tree.
175      * Since the tree is not actually in the component hierarchy it will
176      * never receive this unless we forward it in this manner.
177      */
178     @Override
179     public void updateUI() {
180         super.updateUI();
181         if (tree != null) {
182             tree.updateUI();
183         }
184         // Use the tree's default foreground and background colors in the
185         // table.
186         LookAndFeel.installColorsAndFont(this, "Tree.background",
187                 "Tree.foreground", "Tree.font");
188     }
189 
190     /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to
191      * paint the editor. The UI currently uses different techniques to
192      * paint the renderers and editors and overriding setBounds() below
193      * is not the right thing to do for an editor. Returning -1 for the
194      * editing row in this case, ensures the editor is never painted.
195      */
196     @Override
197     public int getEditingRow() {
198         int rowIndex = -1;
199         final Class<?> editingClass = getColumnClass(editingColumn);
200         if (editingClass != ParseTreeTableModel.class) {
201             rowIndex = editingRow;
202         }
203         return rowIndex;
204     }
205 
206     /**
207      * Overridden to pass the new rowHeight to the tree.
208      */
209     @Override
210     public final void setRowHeight(int newRowHeight) {
211         super.setRowHeight(newRowHeight);
212         if (tree != null && tree.getRowHeight() != newRowHeight) {
213             tree.setRowHeight(getRowHeight());
214         }
215     }
216 
217     /**
218      * Returns tree.
219      * @return the tree that is being shared between the model.
220      */
221     public JTree getTree() {
222         return tree;
223     }
224 
225     /**
226      * Sets text area editor.
227      * @param textArea JTextArea component.
228      */
229     public void setEditor(JTextArea textArea) {
230         editor = textArea;
231     }
232 
233     /**
234      * Sets line position map.
235      * @param linePositionMap Line position map.
236      * @noinspection AssignmentToCollectionOrArrayFieldFromParameter
237      */
238     public void setLinePositionMap(ImmutableList<Integer> linePositionMap) {
239         this.linePositionMap = linePositionMap;
240     }
241 
242     /**
243      * TreeTableCellEditor implementation. Component returned is the
244      * JTree.
245      */
246     private class TreeTableCellEditor extends BaseCellEditor implements
247             TableCellEditor {
248         @Override
249         public Component getTableCellEditorComponent(JTable table,
250                 Object value,
251                 boolean isSelected,
252                 int row, int column) {
253             return tree;
254         }
255 
256         /**
257          * Overridden to return false, and if the event is a mouse event
258          * it is forwarded to the tree.
259          *
260          * <p>The behavior for this is debatable, and should really be offered
261          * as a property. By returning false, all keyboard actions are
262          * implemented in terms of the table. By returning true, the
263          * tree would get a chance to do something with the keyboard
264          * events. For the most part this is ok. But for certain keys,
265          * such as left/right, the tree will expand/collapse where as
266          * the table focus should really move to a different column. Page
267          * up/down should also be implemented in terms of the table.
268          * By returning false this also has the added benefit that clicking
269          * outside of the bounds of the tree node, but still in the tree
270          * column will select the row, whereas if this returned true
271          * that wouldn't be the case.
272          *
273          * <p>By returning false we are also enforcing the policy that
274          * the tree will never be editable (at least by a key sequence).
275          *
276          * @see TableCellEditor
277          */
278         @Override
279         public boolean isCellEditable(EventObject event) {
280             if (event instanceof MouseEvent) {
281                 for (int counter = getColumnCount() - 1; counter >= 0;
282                      counter--) {
283                     if (getColumnClass(counter) == ParseTreeTableModel.class) {
284                         final MouseEvent mouseEvent = (MouseEvent) event;
285                         final MouseEvent newMouseEvent = new MouseEvent(tree, mouseEvent.getID(),
286                                 mouseEvent.getWhen(), mouseEvent.getModifiers(),
287                                 mouseEvent.getX() - getCellRect(0, counter, true).x,
288                                 mouseEvent.getY(), mouseEvent.getClickCount(),
289                                 mouseEvent.isPopupTrigger());
290                         tree.dispatchEvent(newMouseEvent);
291                         break;
292                     }
293                 }
294             }
295 
296             return false;
297         }
298     }
299 }