1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Swing phần 6 ppt

99 283 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Java Swing – O’Reilly - 496 - public JTree(TreeNode root) public JTree(TreeNode root, boolean asksAllowsChildren) These constructors build new trees using the node root as the root of the tree. They also use the DefaultTreeModel as their model. public JTree(TreeModel model) Builds a tree using the model provided. The model argument contains the root of the tree. public JTree(Object value[]) public JTree(Vector value) public JTree(Hashtable value) These convenience constructors build a DefaultTreeModel object and use the inner class JTree.DynamicUtilTreeNode to populate the tree using the value argument as children. If any element in value is itself an Object[], a Vector, or a Hashtable, a node will be built for that element and its contents become children of the node. This recursive process continues until all elements and their contents have been explored. The last constructor is great for simple data structures that you want to display as a tree. Figure 17.7 shows the tree that results when you display a hash table. Figure 17.7. A JTree built using a Hashtable and the DefaultTreeModel Even though this tree is larger than the tree of Figure 17.1, it takes less code to set it up, as follows. // ObjectTree.java // A Simple test to see how we can build a tree and populate it. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; Java Swing – O’Reilly - 497 - import java.util.*; public class ObjectTree extends JFrame { JTree tree; String[][] sampleData = { {"Amy"}, {"Brandon", "Bailey"}, {"Jodi"}, {"Trent", "Garrett", "Paige", "Dylan"}, {"Donn"}, {"Nancy", "Donald", "Phyllis", "John", "Pat"} }; public ObjectTree() { super("Hashtable Test"); setSize(400, 300); addWindowListener(new BasicWindowMonitor()); } public void init() { Hashtable h = new Hashtable(); // build up the hashtable using every other entry in the String[][] as a key // followed by a "value" which is a String[] for (int i = 0; i < sampleData.length; i+=2) { h.put(sampleData[i][0], sampleData[i + 1]); } tree = new JTree(h); getContentPane().add(tree, BorderLayout.CENTER); } public static void main(String args[]) { ObjectTree tt = new ObjectTree(); tt.init(); tt.setVisible(true); } } 17.4.6 Tree Model Methods The JTree class provides two static methods that can build a tree model for use with JTree components. protected static TreeModel getDefaultTreeModel() Creates and populates a "demo" tree. This is useful for visual builders, where you start with an essentially empty tree and add, delete, or configure components graphically. protected static TreeModel createTreeModel(Object value) Generates a tree on the fly by creating a DefaultTreeModel object and populating it with the objects present in value. The value object is quite often an Object array, a Vector, or a Hashtable. The constructors with value arguments use this method. 17.4.7 Selection Methods One of the primary functions the JTree class provides is programmer access to the selection status of the tree. Most of these functions work with a selection model discussed in "Tree Selections." We'll say more about this later, but selections may be based either on rows or paths. A row is a displayed element in a tree; you refer to a row by its index. A path is a list of nodes from the root to the selected node. Java Swing – O’Reilly - 498 - addSelectionInterval(int row1, int row2) Adds the paths between row1 and row2 to the current selection. It uses getPathBetweenRows() to collect the list of paths to add. public void addSelectionPath(TreePath path) public void addSelectionPaths(TreePath paths[]) public void addSelectionRow(int row) public void addSelectionRows(int rows[]) You can use one of these methods to add to the current selection on the tree. If you supply an array of paths or integers, each of the paths or rows indicated will be selected. If any path or row is not currently visible, it will be made visible. public void clearSelection() Clears the current selection completely. public Object getLastSelectedPathComponent() Returns the path component representing the last path entry in the current selection. If the selection is empty, this returns null. public TreePath getLeadSelectionPath() public int getLeadSelectionRow() Return the lead path or row for a selection. A "lead" path is the last path that was added to the selection. public int getMaxSelectionRow() Returns the last row in the current selection. If only one row is selected, that row index is returned. public int getMinSelectionRow() Returns the first row in the current selection. If only one row is selected, that row index is returned. public int getSelectionCount() Returns the number of paths that are currently selected. public TreePath getSelectionPath() public TreePath[] getSelectionPaths() public int[] getSelectionRows() Retrieve the current selected paths (or rows). The getSelectionPath() convenience method returns the first path in the selection. The equivalent method for rows is getMinSelectionRow(). public boolean isPathSelected(TreePath path) Java Swing – O’Reilly - 499 - public boolean isRowSelected(int row) These methods return true if the given path or row is in the current selection. public boolean isSelectionEmpty() Returns true if the selection is currently empty (i.e., nothing is selected). public void removeSelectionInterval(int row1, int row2) Removes the paths between row1 and row2 from the current selection. It uses getPathBetweenRows() to collect the list of paths to deselect. public void removeSelectionPath(TreePath path) public void removeSelectionPaths(TreePath paths[]) public void removeSelectionRow(int row) public void removeSelectionRows(int rows[]) Remove pieces of the current selection dictated by the rows or paths provided as arguments. If a path or row specified in one of these methods is not in the current selection, it is ignored and any remaining rows or paths are deselected. public void setSelectionInterval(int row1, int row2) Sets the current selection to represent the paths between row1 and row2. It uses getPathBetweenRows() to collect the list of paths to select. public void setSelectionPath(TreePath path) public void setSelectionPaths(TreePath paths[]) public void setSelectionRow(int row) public void setSelectionRows(int rows[]) Set the current selection on the tree. If you supply an array of paths or integers, each of the paths or rows indicated will be selected. If any path or row is not currently visible, it will be made visible. 17.4.8 Expansion Methods For any entry in your tree, you can check to see if it is currently expanded or collapsed. A node is considered expanded if all of the nodes in its path are also expanded. (This applies to leaves as well.) You can also programmatically control the collapsing and expanding of parts of your tree. All of the methods below accept either a TreePath or a row (int) argument. public void collapsePath(TreePath path) public void collapseRow(int row) These methods collapse the path or row given if needed. (In the case of the path argument, the last component of the path is collapsed.) Once collapsed, it tries to make the path visible as well. public void expandPath(TreePath path) public void expandRow(int row) Java Swing – O’Reilly - 500 - These methods expand the given path or row if needed. Once expanded, it tries to make the path visible as well. public boolean isCollapsed(int row) public boolean isCollapsed(TreePath path) These methods return true if any node in the given path or row is not currently expanded. If every node is expanded, these methods return false. public boolean isExpanded(int row) public boolean isExpanded(TreePath path) Return true if the given path or row is currently fully expanded. If any nodes in the path are not expanded, these methods return false. public boolean hasBeenExpanded(TreePath path) Returns true if the path has ever been expanded. protected void setExpandedState(TreePath path, boolean state) As long as no TreeWillExpandListener vetoes the move, this helper method sets the state of the path to state, and marks all parents of path as expanded, regardless of the state for path. The JTree class keeps track of the fact that a node has been expanded in a private hashtable called expanded-State. protected void removeDescendantToggledPaths(Enumeration toRemove) Removes references to the descendants of nodes in the toRemove list from the expandedState cache. protected void clearToggledPaths() This method clears the expandedState cache of all entries. 17.4.9 Path and Row Methods public TreePath getClosestPathForLocation(int x, int y) public int getClosestRowForLocation(int x, int y) These methods return the path or row closest to a given location (x,y) in the component, relative to its upper-left corner. These methods only return null if nothing is visible. If you need to be sure that the point (x,y) is actually inside the bounds for the path or row returned, you need to check that yourself. The getPathForLocation() and getRowForLocation() methods do a basic check for you and return null if the point falls outside the closest row, if that's all you need. protected TreePath[] getPathBetweenRows(int row1, int row2) You can use this method to retrieve the various different paths between row1 and row2 (including row2). If no tree exists, this method returns null. This protected method is used by the different selection interval methods. Java Swing – O’Reilly - 501 - public Rectangle getPathBounds(TreePath path) Returns the Rectangle object that encompasses the specified path, if that path is not currently visible. The scrollPathToVisible() method calls this to show a particular path on the screen. If the path is already visible, this method returns null. public TreePath getPathForLocation(int x, int y) This method is a more restricted version of getClosestPathForLocation(). If x or y ends up outside the bounds of the path returned by the closest path call, this method returns null. public TreePath getPathForRow(int row) Returns the path associated with the specified row. If row is an invalid value (less than zero or greater than the number of rows in the current tree), or the row is not currently visible, this method returns null. public Rectangle getRowBounds(int row) This method functions like getPathBounds() for the given row. public int getRowCount() Returns the number of rows that are currently visible. See the isVisible() method below. public int getRowForLocation(int x, int y) This method is a more restricted version of getClosestRowForLocation(). If x or y ends up outside the bounds of the row returned by the closest row call, this method will return -1. public int getRowForPath(TreePath path) Returns the row number for the last component in path. If any part of path is not visible, or path is null, this method returns -1. public boolean isVisible(TreePath path) Returns true if the path given is currently visible. A "visible" path is any path you can see in the tree without expanding another node. If you have the tree in a scroll pane, a path could be off the screen, but still be considered visible. public void makeVisible(TreePath path) Makes path visible, if it is not already visible. public void scrollPathToVisible(TreePath path) public void scrollRowToVisible(int row) If the tree is in a scroll pane, scroll the given path or row to make it appear in the pane. A path is expanded up to its last component, if need be, to make it visible. (By definition, rows are always visible.) The tree must be in a scrollable environment (like a JScrollPane or JViewport) for this to work. Java Swing – O’Reilly - 502 - 17.4.10 Editing Methods public void cancelEditing() Cancels editing of a tree cell. If no cell is being edited, this method has no effect. public TreeNode getEditingPath() Returns the path to the element in the tree that is currently being edited. If the tree is not being edited, this method returns null. public boolean isEditing() Returns true if the current selection is being edited. public boolean isPathEditable(TreePath path) Returns the value of the editable property for a given path. If it returns true, the path can be edited. It gets called by the UI manager before starting to edit a node so that a subclass of JTree can override this method and say yes or no based on some appropriate criteria. (For example, you could allow editing of leaves, but not allow editing of folders.) public void startEditingAtPath(TreePath path) Tries to start editing the last element in path. This might fail if the cell editor will not edit that element. public boolean stopEditing() Stops the tree from being edited. If the tree is not being edited, then this method has no effect. It returns true if the tree was being edited, and the cell editor stopped successfully. It returns false otherwise — for example, if the tree was not being edited or the editor could not be stopped. 17.4.11 Miscellaneous Methods public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) Converts value to a string for the cell's renderer by calling value. toString(). You could subclass JTree and override this to prepare a more meaningful string. public String getToolTipText(MouseEvent event) Returns the tooltip text from a cell's renderer. For this to work properly, however, this JTree must be registered manually with the ToolTipManager , and your cell renderer must have some tooltip text: ToolTipManager.sharedInstance().registerComponent(tree); ((JComponent)tree.getCellRenderer()).setToolTipText("This is a tip."); Java Swing – O’Reilly - 503 - The default renderer displays the same tip for every cell in your tree. To get more interesting tips, you'll need to create your own renderer. An example of such a renderer is discussed later in the "Custom Renderers" section. public void treeDidChange() Updates the tree when nodes have expanded or collapsed, or when nodes have been inserted. protected TreeModelListener createTreeModelListener() This method returns a new TreeModelHandler object (see Section 17.4.12) for use with this tree. The TreeModelHandler manages the private expandedState hashtable. 17.4.12 JTree Inner Classes protected class JTree.AccessibleJTree This class represents the accessible implementation for JTree. public static class JTree.DynamicUtilTreeNode Various constructors of the JTree class use this inner class to build tree nodes out of arrays, vectors and hashtables. protected static class JTree.EmptySelectionModel As its name implies, this inner class provides an implementation of the TreeSelectionModel interface (by extending DefaultTreeSelectionModel) that does not allow any selections. protected class JTree.TreeModelHandler This class manages the expandedState cache by listening to expansion and modification events coming from the model. protected class JTree.TreeSelectionRedirector This class contains methods for redirecting the source of events. Typically this is done when the tree model generates an event, but the JTree object associated with that model needs to be listed as the source of the event. 17.4.13 UI Methods The methods in this group (with the exception of UpdateUI()) implement the scrollable interface, which allow a JScrollPane or JViewport to be "intelligent" when scrolling a JTree. public Dimension getPreferredScrollableViewportSize() Returns the preferred size of a scrollable viewport for this tree based on the visible row count (for height) and the current preferred width. public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) Java Swing – O’Reilly - 504 - Returns the appropriate block increment (the amount needed to expose one "page" or "screen") for the viewport's scrollbars based on this tree and the parameters provided. The visibleRect argument is the viewable area of the viewport. Its size determines how much to scroll. You can use either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL for orientation, and direction takes -1 for up or left, and 1 for down or right. public boolean getScrollableTracksViewportHeight() public boolean getScrollableTracksViewportWidth() Both of these methods return false to indicate that changing the size of the viewport containing the tree does not affect the calculated width or height of the tree. They can be overridden for specialized behavior. For example, if you placed your tree in a JScrollPane and the width of that pane were suddenly changed so that a given node might not be visible without scrolling, you could turn on tooltips for the long node and supply a string that contained the entire path for that node. The tooltip popup would show the whole path without scrolling, regardless of the viewport size. public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) Returns the amount needed to expose the next row. If the direction is HORIZONTAL, it returns 4. public void updateUI() Overrides the JComponent updateUI() call to replace the tree's UI with the version from the interface manager. As with other components, you can use this to refresh the tree after the look-and-feel has changed. 17.5 Tree Selections After you have the tree built and looking the way you want it to, you need to start working with selections so it does something useful. The JTree class introduced many of the selection manipulation methods already, but let's take a closer look at the model for selecting paths in a tree and the DefaultSelectionModel provided in the javax.swing.tree package. If you're comfortable with selection models, you probably won't find anything surprising here and may want to skip to "Editing and Rendering." Selections are based on rows or paths. It's important to realize the distinction between a "row" and a "path" for trees. A path contains the list of nodes from the root of the tree to another node. Paths exist regardless of whether or not you plan to display the tree. Rows, however, are completely dependent on the graphical display of a tree. The easiest way to think about a row is to think of the tree as a JList object. Each item in the list is a row on the tree. That row corresponds to some particular path. As you expand and collapse folders, the number of rows associated with the tree changes. It's the RowMapper object's job to relate a row number to the correct path. Depending on your application, you may find rows or paths more efficient to deal with. If your program deals mostly with the user object data, paths will most likely be the thing to use. If you're working with the graphical interface (automatically expanding folders and things like that) the rows may be more useful. Java Swing – O’Reilly - 505 - 17.5.1 The RowMapper Interface Tree selections make extensive use of the RowMapper interface. It is a simple interface with one method: public int[] getRowsForPaths(TreePath paths[]) The UI for your tree should implement this to return a list of row indices matching the paths supplied. If any of the paths are null or not visible, a -1 should be placed in the return int array. While this may seem like an obvious task, you must account for the expanded or collapsed state of the nodes in the tree; remember that there's no such thing as a collapsed row. This is one reason the JTree class cannot simply use a ListSelectionModel. 17.5.2 The TreeSelectionModel Interface Now for the heart of selections. The TreeSelectionModel determines what a tree selection can look like. 17.5.2.1 Properties The TreeSelectionModel contains the properties listed in Table 17.11. The selection model properties deal primarily with the current selection on the tree. The notion of a "lead" selection stems from the fact that a selection can happen as a process, not only as a single event. The lead selection is the most recently added cell in the selection. It might be the only path selected, but it might also be the most recent selection out of several in a range or discontiguous group of selections. If the selection contains more than one path, the getSelectionPath() method returns the first selection in the path, which may or may not be the same thing as getLeadSelectionPath(). It's also good to remember that selecting a "folder" node in a tree does not imply selecting all of the nodes underneath it, if it has children. Having said that, the rest of the properties are fairly self-explanatory. minSelectionRow and maxSelectionRow let you get the smallest and largest selected row numbers. rowMapper holds a utility that manages the mapping between rows and row numbers. selectionPaths and selectionRows let you access the rows or paths that are currently selected. selectionCount tells you the number of rows that are selected. Table 17.11, TreeSelectionModel Properties Property Data Type get is set bound Default Value leadSelectionPath TreePath leadSelectionRow int maxSelectionRow int minSelectionRow int rowMapper RowMapper selectionCount int selectionMode int selectionPath TreePath selectionPaths TreePath[] selectionRows int[] selectionEmpty boolean 17.5.2.2 Constants [...]... this property only has an effect when you are using the Metal look-and-feel - 518 - Java Swing – O’Reilly // TestTree3 .java // A Simple test to see how we can build a tree and customize its icons // import java. awt.*; import java. util.*; import java. awt.event.*; import javax .swing. *; import javax .swing. plaf.*; import javax .swing. tree.*; public class TestTree3 extends JFrame { JTree tree; DefaultTreeModel... editor // ExpressionTreeCellEditor .java // A customized editor for our expression tree This editor only kicks in if the - 528 - Java Swing – O’Reilly // node you try to edit is an OpNode, otherwise the default text field is used // for integers // import javax .swing. *; import javax .swing. event.*; import java. awt.*; import java. awt.event.*; import java. util.*; import javax .swing. tree.*; public class ExpressionTreeCellEditor... ExpressionTreeCellRenderer .java // A renderer for our expression cells // import java. awt.*; import javax .swing. *; import javax .swing. tree.*; public class ExpressionTreeCellRenderer extends JLabel implements TreeCellRenderer { Color backColor; boolean isLeaf; public ExpressionTreeCellRenderer() { } // Pick a nice, big, fixed width font for our labels setFont(new Font("Monospaced", Font.PLAIN, 16) ); setHorizontalAlignment(SwingConstants.CENTER);... clicks on our node with the right mouse button // EditorComboBox .java // A CellEditor JComboBox subclass for use with Trees (and possibly tables) This // particular editor also checks to verify that the value entered is an integer // import javax .swing. *; import javax .swing. event.*; import java. awt.event.*; import java. awt.*; import java. util.*; public class EditorComboBox extends JComboBox implements... methods ensure that any time the tree changes, we re-evaluate the expression // EvaluatorLabel .java // An extension of the JLabel class // tree This class is specifically // objects, but it returns a double // interesting value instead of 0 // import javax .swing. *; import javax .swing. event.*; import javax .swing. tree.*; that evaluates the value of an expression designed to work with OpNodes and Integer... node 17 .6. 5.1 Fields protected TreePath path Stores the path associated with this event 17 .6. 5.2 Constructors public TreeExpansionEvent(Object source, TreePath path) The source for this constructor is most often the tree itself, but it's certainly possible to imagine a GUI trigger being considered the source for a collapse or expand call 17 .6. 5.3 Methods public TreePath getPath() - 514 - Java Swing –... updates the lastPath field as things change 17.7.7 .6 CellEditor and TreeCellEditor Methods The DefaultTreeCellEditor class implements the TreeCellEditor interface (and by extension, the CellEditor interface) The methods from those interfaces are present in the class The methods for CellEditor are usually delegated to the realEditor component - 5 26 - Java Swing – O’Reilly public Component getTreeCellEditorComponent(JTree... selection If the selection is null, the leadIndex property is reset to -1 17 .6 Tree Events Trees generate three new types of events that are worth mentioning Apart from the obvious selection and expansion events from the graphical side, you can also catch structural changes with model events - 509 - Java Swing – O’Reilly 17 .6. 1 The TreeModelEvent Class The TreeModelEvent class encapsulates model changes... fireTreeCollapsed() methods are never called 17 .6. 7.3 Constructors public ExpandVetoException(TreeExpansionEvent event) public ExpandVetoException(TreeExpansionEvent event, String message) - 515 - Java Swing – O’Reilly Similar to other exception classes, these constructors build new exceptions with the proposed expansion event, and an optional message 17 .6. 7.4 Fields protected TreeExpansionEvent event... clearSelection(), this method should have no effect public boolean isPathSelected(TreePath path) public boolean isRowSelected(int row) Return true if the path or row specified is in the current selection - 5 06 - Java Swing – O’Reilly public void removeSelectionPath(TreePath path) public void removeSelectionPaths(TreePath paths[])) Remove the listed path or paths from the current selection Any selected paths not . ObjectTree .java // A Simple test to see how we can build a tree and populate it. // import java. awt.*; import java. awt.event.*; import javax .swing. *; import javax .swing. tree.*; Java Swing –. will show an // interesting value instead of 0 . . . // import javax .swing. *; import javax .swing. event.*; import javax .swing. tree.*; public class EvaluatorLabel extends JLabel implements. selectionRows int[] selectionEmpty boolean 17.5.2.2 Constants Java Swing – O’Reilly - 5 06 - The value of the selectionMode property must be one of the constants listed in

Ngày đăng: 12/08/2014, 19:21

Xem thêm: Java Swing phần 6 ppt

TỪ KHÓA LIÊN QUAN