Thursday 30 March 2017

Trees & Tables - Java Tutorials

Trees

A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which extends JComponent. Some of its constructors are shown here:

      JTree(Hashtable ht)
      JTree(Object obj[ ])
      JTree(TreeNode tn)
      JTree(Vector v)

The first form creates a tree in which each element of the hash table ht is a child node. Each element of the array obj is a child node in the second form. The tree node tn is the root of the tree in the third form. Finally, the last form uses the elements of vector v as child nodes.

A JTree object generates events when a node is expanded or collapsed. The addTreeExpansionListener( ) and removeTreeExpansionListener( ) methods allow listeners to register and unregister for these notifications. The signatures of these methods are shown here:

      void addTreeExpansionListener(TreeExpansionListener tel)
      void removeTreeExpansionListener(TreeExpansionListener tel)

Here, tel is the listener object. The getPathForLocation( ) method is used to translate a mouse click on a specific point of the tree to a tree path. Its signature is shown here:

      TreePath getPathForLocation(int x, int y)

Here, x and y are the coordinates at which the mouse is clicked. The return value is a TreePath object that encapsulates information about the tree node that was selected by the user.

The TreePath class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. In this book, only the toString( ) method is used. It returns a string equivalent of the tree path.

The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node. The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here:

      DefaultMutableTreeNode(Object obj)

Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children. To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here:

      void add(MutableTreeNode child)

Here, child is a mutable tree node that is to be added as a child to the current node. Tree expansion events are described by the class TreeExpansionEvent in the javax.swing.event package. The getPath ( ) method of this class returns a TreePath object that describes the path to the changed node. Its signature is shown here:

      TreePath getPath( )

The TreeExpansionListener interface provides the following two methods:

      void treeCollapsed(TreeExpansionEvent tee)
      void treeExpanded(TreeExpansionEvent tee)

Here, tee is the tree expansion event. The first method is called when a subtree is hidden, and the second method is called when a subtree becomes visible. Here are the steps that you should follow to use a tree in an applet:
  1. Create a JTree object.
  2. Create a JScrollPane object. (The arguments to the constructor specify the tree and the policies for vertical and horizontal scroll bars.)
  3. Add the tree to the scroll pane.
  4. Add the scroll pane to the content pane of the applet.

The following example illustrates how to create a tree and recognize mouse clicks on it. The init( ) method gets the content pane for the applet. A DefaultMutableTreeNode object labeled “Options” is created. This is the top node of the tree hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll pane is then added to the applet. Next, a text field is created and added to the applet. Information about mouse click events is presented in this text field. To receive mouse events from the tree, the addMouseListener( ) method of the JTree object is called. The argument to this method is an anonymous inner class that extends MouseAdapter and overrides the mouseClicked( ) method.

The doMouseClicked( ) method processes mouse clicks. It calls getPathForLocation( ) to translate the coordinates of the mouse click into a TreePath object. If the mouse is clicked at a point that does not cause a node selection, the return value from this method is null. Otherwise, the tree path can be converted to a string and presented in the text field.

  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  import javax.swing.tree.*;
  /*
    <applet code="JTreeEvents" width=400 height=200>
    </applet>
  */

  public class JTreeEvents extends JApplet {
    JTree tree;
    JTextField jtf;

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();

      // Set layout manager
      contentPane.setLayout(new BorderLayout());

      // Create top node of tree
      DefaultMutableTreeNode top = new DefaultMutableTreeNode
                                       ("Options");

      // Create subtree of "A"
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      top.add(a);
      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
      a.add(a2);

      // Create subtree of "B"
      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      top.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
      b.add(b1);
      DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
      b.add(b2);
      DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
      b.add(b3);

      // Create tree
      tree = new JTree(top);

      // Add tree to a scroll pane
      int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
      int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
      JScrollPane jsp = new JScrollPane(tree, v, h);

      // Add scroll pane to the content pane
      contentPane.add(jsp, BorderLayout.CENTER);
  
      // Add text field to applet
      jtf = new JTextField("", 20);
      contentPane.add(jtf, BorderLayout.SOUTH);

      // Anonymous inner class to handle mouse clicks
      tree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
          doMouseClicked(me);
        }
      });
    }

    void doMouseClicked(MouseEvent me) {
      TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
      if(tp != null)
        jtf.setText(tp.toString());
      else
        jtf.setText("");
    }
  }

The string presented in the text field describes the path from the top tree node to the selected node.




Tables

A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent. One of its constructors is shown here:

      JTable(Object data[ ][ ], Object colHeads[ ])

Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.

Here are the steps for using a table in an applet:
  1. Create a JTable object.
  2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.)
  3. Add the table to the scroll pane.
  4. Add the scroll pane to the content pane of the applet.

The following example illustrates how to create and use a table. The content pane of the JApplet object is obtained and a border layout is assigned as its layout manager. A one-dimensional array of strings is created for the column headings. This table has three columns. A two-dimensional array of strings is created for the table cells. You can see that each element in the array is an array of three strings. These arrays are passed to the JTable constructor. The table is added to a scroll pane and then the scroll pane is added to the content pane.

  import java.awt.*;
  import javax.swing.*;
  /*
    <applet code="JTableDemo" width=400 height=200>
    </applet>
  */

  public class JTableDemo extends JApplet {

    public void init() {

      // Get content pane
      Container contentPane = getContentPane();

      // Set layout manager
      contentPane.setLayout(new BorderLayout());

      // Initialize column headings
      final String[] colHeads = { "Name", "Phone", "Fax" };

      // Initialize data
      final Object[][] data = {
        { "Gail", "4567", "8675" },
        { "Ken", "7566", "5555" },
        { "Viviane", "5634", "5887" },
        { "Melanie", "7345", "9222" },
        { "Anne", "1237", "3333" },
        { "John", "5656", "3144" },
        { "Matt", "5672", "2176" },
        { "Claire", "6741", "4244" },
        { "Erwin", "9023", "5159" },
        { "Ellen", "1134", "5332" },
        { "Jennifer", "5689", "1212" },
        { "Ed", "9030", "1313" },
        { "Helen", "6751", "1415" }
      };

      // Create the table
      JTable table = new JTable(data, colHeads);

      // Add table to a scroll pane
      int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
      int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
      JScrollPane jsp = new JScrollPane(table, v, h);

      // Add scroll pane to the content pane
      contentPane.add(jsp, BorderLayout.CENTER);
    }
  }


Exploring Swing

As mentioned earlier, Swing is a large system, and it has many features that you will want to explore on your own. For example, Swing provides toolbars, tooltips, and progress bars. Also, Swing components can provide a pluggable look and feel, which means that it is easy to substitute another appearance and behavior for an element. This can be done dynamically. You may even design your own look and feel. Frankly, the Swing approach to GUI components might replace the AWT classes some time in the future, so familiarizing yourself with it now is a good idea.

Swing is just one part of the Java Foundation Classes (JFC). You may want to explore other JFC features. The Accessibility API can be used to build programs that are usable by people with disabilities. The Java 2-D API provides advanced capabilities for working with shapes, text, and images. The Drag-and-Drop API allows information to be exchanged between Java and non-Java programs.

No comments:

Post a Comment