Unit 5 swing & TREES

1,486 views
1,428 views

Published on

FULL SWING UNIT
BY:- SHARAFAT ALI MEWATI

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,486
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Unit 5 swing & TREES

  1. 1. TREES –Many tree structures arise in everyday life,such as thehierarchyof countries ,states & cities.The Swing library has a JTreeclass for this purpose.The JTree class takes care of layingout the tree and processing user requests for expandingand collapsingnodes. A tree is composed of nodes.Every node is either aleaf or it has child nodes.Everynode,with the exception ofthe root node, has exactly one parent.A tree has exactlyone root node. Sometimes you have a collection of trees,each of which has its own root node.Such a collection iscalled a forest. (draw diagram on page no 358 Fig 6.7 )Simple Trees -The JTree component follows the model view-controllerpattern. You provide a model of the hierarchical data, andthe componentdisplays it for you. To construct a JTree, you supply thetree model in the constructor : TreeModel model=. . . ; JTreee tree = new JTree(model) ;
  2. 2. To construct a default tree model, you must supply a rootnode. TreeNode root = . . . ; DefaultTreeModel model=newDefaultTreeModel(root) ;TreeNode is another interface.you can simply pass the root node to the JTreeconstructor.Then the tree automatically constructs a default treemodel : JTree tree =new JTree(root) ;Editing Trees and Tree Paths -The JTree class has a surprising way of identifying nodes ina tree. It doesnot deal with tree nodes, but with paths ofobjects,called tree paths. A tree path starts at the root &consists of a sequence of child nodes. (draw diagram on page no 366 Fig 6-18)The JTree class knows nothing about the TreeNodeinterface.That interace is never used by the TreeModelinterface.it is only used by the DefaultTreeModelimplementation.You can have other tree models in whichthe nodes do not implement the TreeNode interface atall.If you use a tree model that manages other types ofobjects, then those objects may not have getParent &getChild methods.
  3. 3. The TreePath class manages a sequence of Objectreferences.A number of JTree methods return Treepath objects.Whenyou have a tree path,you usually just need to Knowthe terminal node,which you get with thegetLastPathComponent method.For eg, to find out thecurrently selected node in a tree, you use thegetSelectionPath method of the JTreeclass.You get a TreePath object back, from which you canretrieve the actual node. TreePath selectionPath= tree.getSelectionPath() ; DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent() ;If you use the insertNodeInto method of theDefaultTreeModel class, the model class takes care of that.For eg, thefollowing call appends a new node as the last child of theselected node & notifies the tree view.model.insertNodelnto(newNode, selectedNode ,selectedNode.getchildCount()) ;The analogous call removeNodeFromParent removes anode and notifies the view: model.removeNodeFromParent (selectedNode) ;Node Enumeration -
  4. 4. Sometimes you need to find a node in a tree by starting atthe root & visiting all children until you have found amatch.The DefaultMutableTreeNode class has severalmethods for iterating through nodes.The breadthFirstEnumeration & depthFirstEnumerationmethods return enumeration objects whose nextElementmethod visits all children of the current node,using eithera breadth-first or depth-first traversal.Breadth-first enumeration is the easiest to visualize.Thetree is traversed in layers.The root is visited first,followedby all of its children, then followed by the grandchildren,and soon.To visualize depth-first enumeration,imagine a rattrapped in a tree-shaped maze. It rushes along the firstpath until it comes to a leaf.Then, it backtracks and turnsaround tothe next path, and so on.The postOrderTraversal method is a synonym fordepthFirstTraversal because the search process visits thechilden before visiting the parents.Here is the typical usage pattern:Enumeration breadthFirst =node.breadthFirstEnumeration() ;while (breadthFirst.hasMoreElements())do something with breadthFirst. nextElement();Finally,a method, pathFromAncestorEnumeration, finds apath from an ancestor to a given node and thenenumerates
  5. 5. the nodes along that path. (draw diagram on page no 373 Fig 6-22)Rendering Nodes- you will often need to change the way in which a treecomponentdraws the nodes.The most common change is to choosedifferent icons for nodes and leaves.Other changes mightinvolve changing the font of the node labels or drawingimages at the nodes. All these changes are made possibleby installing a new treecell renderer into the tree.By default, the JTree class usesDefaultTreeCellRenderer objects to draw each node.TheDefaultTreeCellRenderer class extends the JLabelclass. Thelabel contains the node icon and the node label.You can customize the display in three ways :1. You can change the icons, font, and background colorused by a DefaultTreeCellRenderer.These settings are usedfor all nodes in the tree.2. You can install a renderer that extends the DefaultTreeCellRenderer class and vary the icons,fonts, and background color for each node.3. You can install a renderer that implements the TreeCellRenderer interface, to draw a custom
  6. 6. image for each node.To change the appearance of individual nodes,you install atree cell renderer.The TreeCellRenderer interface has asingle method:Component getTreeCellRendererComponent(JTree tree,Object value, boolean selected,boolean expanded, boolean leaf, int row, booleanhasFocus)Custom Tree Models -The TreeModel interface has only a handful ofmethods.The first group of methods enables the JTree tofind the tree nodes by first getting the root, then thechildren.The JTree class calls these methods only when theuser actually expands a node. Object getRoot () int getChildCount(Object parent) Object getChild(Object parent, int index)TheTreeModel is responsible for telling the JTree how theyare connected.The next method of the TreeModelinterface is the reverse of getChild: int getlndexOfChild(Object parent,Object child)The tree model tells the JTree which nodes should bedisplayed as leaves: boolean isLeaf(Object node)
  7. 7. If your code changes the tree model, then the tree needsto be notified so that it can redraw itself. The tree addsitself as a TreeModelListener to the model.Thus, themodel must supportthe usual listener management methods: void addTreeModelListener(TreeModelListener l) void removeTreeModelListener(TreeModelListener l)When the model modifies the tree contents, it calls one ofthe four methods of the TreeModelListener interface: void treeNodesChanged(TreeModelEvent e) void treeNodeslnserted(TreeModelEvent e) void treeNodesRemoved (TreeModelEvent e ) void treeStructureChanged(TreeModelEvent e)The TreeModelEvent object describes the location of thechange.Finally if the user edits a tree node, your model is calledwith the change. Void valueForPathChanged(TreePath path ,ObjectnewValue)If you don’t allow editing, this method is never called.Progress Indicators -A JProgressBar is a Swing component that indicatesprogress. A ProgressMonitor is a dialog box that contains aprogress bar. A ProqressMonitorInputStream displays aprogress monitor
  8. 8. dialog box while the stream is read.Progress BarsA progressbar is a simple component-just a rectangle thatis partially filled with color to indicate the progress of anoperation. By default, progress is indicated by a string “n%“.You construct a progress bar much as you construct aslider, by supplying the minimum and maximum value andan optional orientation: progressBar = newJProgressBar(0, 1000); progressBar= newJProgressBar(SwingConstants.VERTICAL, 0, 1000);You can also set the minimum and maximum with thesetMinimum and setMaximum methods.Unlike a slider,the progress bar cannot be adjusted by theuser. Your program needs to call setValueto update it.If you call progressBar. setStringPainted(true);the progress bar computes the completion percentage anddisplays a string ”n% “ .If you want to show a differentstring, you can supply it with the setString method: if (progressBar.getValue() > 900) progressBar.setString(" AlmostDone "); (draw diagram on page no 436 Fig 6-41)Progress Monitor
  9. 9. A ProgressMonitor is a complete dialog box that contains aprogress bar.The dialog box contains a Cancel button.Ifyou click it,the monitor dialog box is closed.Inaddition,your program can query whether the user hascanceled the dialog box & terminate the monitored action.You construct a progress monitor by supplying thefollowing:  The parent component over which the dialog box should pop up.  An object that is displayed on the dialog box.  An optional note to display below the object.  The minimum and maximum values. .As you update the progress value, you should also call theisCanceled method to see if the program user has clickedtheCancel button. (draw diagram on page no 441 fig 6-42)When the monitored activity has concluded, call the closemethod to dismiss the dialog box.You can reuse the samedialog box by calling start again.There are two conditions for termination. The activitymight have completed, or the user might have canceled it.In each of these cases, we close down :  The timer that monitored the activity.  The progress dialog box.  The activity itself (by interrupting the thread).
  10. 10. Component Organizers –These include the split pane, a mechanism for splitting anarea into multiple parts whose boundaries canbeadjusted,the tabbed pane,which uses tab dividers to allowa user to flip through multiple panels,& the desktoppane.,which can be used to implement applications thatdisplay multiple internal frames.Split Pane -Split panes split a component into two parts,with anadjustable boundary in.The outer pane is splitvertically,with a text area on the bottom & another splitpane on the top.That pane is split horizontally,with a liston the left & a label containing an image on the right.You construct a split pane by specifying the orientation,one of JSplitPane.HORIZONTAL_SPLIT orJSplitPane.VERTICAL_SPLIT followed by the twocomponents.For eg-JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAl_SPLIT, planetList, planetImage) ;If you like, you can add "one-touch expand" icons to thesplitterbar. (draw diagram on page no 450 )
  11. 11. In the Metal look and feel, they are small triangles. If youclick one of them, the splitter moves all the way in thedirection towhich the triangle is pointing, expanding one of the panescompletely.To add this capability, call innerPane. setOneTouchExpandable(true) ;The "continuous layout" feature continuously repaints thecontents of both components as the user adjusts thesplitter.You turn on that feature with the call innerPane.setContinuousLayout(true) ;In the example program, we left the bottom splitter at thedefault (no continuous layout).When you drag it, you onlymove a black outline. When you release the mouse, thecomponents are repainted.Tabbed Panes –To remove a tab from the tab collection,use tabPane.removeTabAt(index);When you add a new tab to the tab collection.It is notautomatically displayed.You must select it with thesetSelectedIndex method. For eg - here is how you show atab that you just added to the end: tabbedPane.setSelectedIndex(tabbedPane.getTabCount() -1) ; You set the tab layout to wrapped or scrolling mode bycalling
  12. 12. tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_ TAB_LAYOUT) ;ortabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);To be notified whenever the user clicks on a new tab,youinstall a ChangeListener with the tabbed pane. tabbedPane.addChangeListener(listener) ;when the user selects a tab, the stateChanged method ofthe change listener is called.You retrieve the tabbed paneas the source of the event.Call the getSelectedIndexmethod to find out which pane is about to be displayed. Public void stateChanged(ChangeEvent event) { int n=tabbedPane.getSelectedIndex() ; loadTab( n) ; } (draw diagram on page no 454 fig 6-46)

×