Advanced Java Lecture 10
Advanced Java Lecture 10
To construct this list component, you first start out with an array of
strings, then pass the array to the JList constructor:
String[] words= { "quick", "brown", "hungry", "wild", ... };
JList wordList = new JList(words);
Alternatively, you can use an anonymous array:
JList wordList = new JList(new String[] {"quick", "brown", "hungry", "wild", ... });
To make a list box scroll, you must insert it into a scroll pane:
JScrollPane scrollPane = new JScrollPane(wordList);
By default, the list component displays eight items; use the setVisibleRowCount
method to change that value:
wordList.setVisibleRowCount(4); // display 4 items
Event Handling
Trees
Every computer user who uses a hierarchical file system has
encountered tree displays such as the one in Fig below
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
The Jtree class (together with helper classes) takes care of laying out the
tree and processing user requests for expanding and collapsing nodes.
Tree terminology
Simple Trees
As with most other Swing components, the Jtree component follows the
model-view-controller pattern. You provide a model of the hierarchical
data, and the component displays it for you. To construct a Jtree, you
supply the tree model in the constructor:
DefaultTreeModel model = . . .;
JTree tree = new JTree(model);
public MyTree()
{
JTree jtr;
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Color");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Black");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Blue");
DefaultMutableTreeNode child21 = new DefaultMutableTreeNode("Navy Blue");
DefaultMutableTreeNode child22 = new DefaultMutableTreeNode(" DarkBlue");
DefaultMutableTreeNode child3 = new DefaultMutableTreeNode("Green");
DefaultMutableTreeNode child4 = new DefaultMutableTreeNode("White");
root.add(child1);
root.add(child2);
root.add(child3);
root.add(child4);
child2.add(child21);
child2.add(child22);
Jtr=new JTree(root);
c.add(root);
// TODO add your handling code here:
}