Hiding leaf node from jtree ?
Hi,
How can I hide all nodes that are leafs on a tree?
Basically, I'm creating a splitpane where on the left side I have a jtree where when a user clicks on a node ( as a folder ) on that jtree the leaf nodes ( all the children nodes of the selected node ) will appear on the right split pane as icons.
thanks in advance!
Define your own renderer class eg:
class NavTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
if(leaf == true){
this.setPreferredSize(new Dimension(0, 0));
super.getTreeCellRendererComponent(tree, dto.getNodeLabel(), sel, expanded, true, row, hasFocus);
return this;
Then set this rederer to ur tree
NavTreeCellRenderer navTCR = new NavTreeCellRenderer();
jTree.setCellRenderer(navTCR);
And then ENJOY
Similar Messages
-
Hide leaf nodes from jtree.
Hi,
How can I hide all nodes that are leafs on a tree? Basically, I'm creating a splitpane where on the left side I have a jtree where when a user clicks on a node on that jtree the leaf nodes will appear on the right split pane as icons.
VThanks for the reply...
I wanted to include the leaf nodes in the tree model so that I won't need to work with two data structures--one with the leaf nodes, and another without the leaf nodes.
So far, I think I resolved the problem. I created my own treemodel class where I pass a defaulttreemodel into it and created a modified getChildCount which will go into the defaulttreemodel and filter out the leaf nodes.
It all seems to work pretty well.
My problem now... How do I remove the stupid node icons? :)
I just want the dashed lines to appear and nothing more....
Thanks again...
V -
Hiding a intermediate node in a Jtree without hiding leaf nodes
Hi who can help me out of this problem. What my prob is dat i m interrested in hiding few intermediate nodes in JTree without hiding their children.
Thanks
Rakeshbut how do you then expand to see the children? once the node is hidden, can you by any means expand/collapse it to view/hide the child leaves?
-
Remove white space nodes from jtree
I am trying to create jtree using XML DOM.
But I m not able to remove/ignore the white space elements from DOM.
I am getting output something like this
for example
Server
Text
node1
Text
I want something like this.
Server
node1
I tried all option for removeing the white space
Here I am posting the source
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
// Basic GUI components
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
// GUI components for right-hand side
import javax.swing.JSplitPane;
import javax.swing.JEditorPane;
// GUI support classes
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
// For creating borders
import javax.swing.border.EmptyBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
// For creating a TreeModel
import javax.swing.tree.*;
import javax.swing.event.*;
import java.util.*;
public class DomEcho02 extends JPanel
// Global value so it can be ref'd by the tree-adapter
static Document document;
static final int windowHeight = 460;
static final int leftWidth = 300;
static final int rightWidth = 340;
static final int windowWidth = leftWidth + rightWidth;
public DomEcho02()
// Make a nice border
EmptyBorder eb = new EmptyBorder(5,5,5,5);
BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
CompoundBorder cb = new CompoundBorder(eb,bb);
this.setBorder(new CompoundBorder(cb,eb));
// Set up the tree
JTree tree = new JTree(new DomToTreeModelAdapter());
// Iterate over the tree and make nodes visible
// (Otherwise, the tree shows up fully collapsed)
//TreePath nodePath = ???;
// tree.expandPath(nodePath);
// Build left-side view
JScrollPane treeView = new JScrollPane(tree);
treeView.setPreferredSize(
new Dimension( leftWidth, windowHeight ));
// Build right-side view
JEditorPane htmlPane = new JEditorPane("text/html","");
htmlPane.setEditable(false);
JScrollPane htmlView = new JScrollPane(htmlPane);
htmlView.setPreferredSize(
new Dimension( rightWidth, windowHeight ));
// Build split-pane view
JSplitPane splitPane =
new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
treeView,
htmlView );
splitPane.setContinuousLayout( true );
splitPane.setDividerLocation( leftWidth );
splitPane.setPreferredSize(
new Dimension( windowWidth + 10, windowHeight+10 ));
// Add GUI components
this.setLayout(new BorderLayout());
this.add("Center", splitPane );
} // constructor
public static void main(String argv[])
if (argv.length != 1) {
System.err.println("Usage: java DomEcho filename");
System.exit(1);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
//factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse( new File(argv[0]) );
makeFrame();
} catch (SAXException sxe) {
// Error generated during parsing)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
} // main
public static void makeFrame() {
// Set up a GUI framework
JFrame frame = new JFrame("DOM Echo");
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
// Set up the tree, the views, and display it all
final DomEcho02 echoPanel =
new DomEcho02();
frame.getContentPane().add("Center", echoPanel );
frame.pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
int w = windowWidth + 10;
int h = windowHeight + 10;
frame.setLocation(screenSize.width/3 - w/2,
screenSize.height/2 - h/2);
frame.setSize(w, h);
frame.setVisible(true);
} // makeFrame
// An array of names for DOM node-types
// (Array indexes = nodeType() values.)
static final String[] typeName = {
"none",
"Element",
"Attr",
"Text",
"CDATA",
"EntityRef",
"Entity",
"ProcInstr",
"Comment",
"Document",
"DocType",
"DocFragment",
"Notation",
// This class wraps a DOM node and returns the text we want to
// display in the tree. It also returns children, index values,
// and child counts.
public class AdapterNode
org.w3c.dom.Node domNode;
// Construct an Adapter node from a DOM node
public AdapterNode(org.w3c.dom.Node node) {
domNode = node;
// Return a string that identifies this node in the tree
// *** Refer to table at top of org.w3c.dom.Node ***
public String toString() {
String s = typeName[domNode.getNodeType()];
String nodeName = domNode.getNodeName();
if (! nodeName.startsWith("#")) {
s += ": " + nodeName;
if (domNode.getNodeValue() != null) {
if (s.startsWith("ProcInstr"))
s += ", ";
else
s += ": ";
// Trim the value to get rid of NL's at the front
String t = domNode.getNodeValue().trim();
int x = t.indexOf("\n");
if (x >= 0) t = t.substring(0, x);
s += t;
return s;
* Return children, index, and count values
public int index(AdapterNode child) {
//System.err.println("Looking for index of " + child);
int count = childCount();
for (int i=0; i<count; i++) {
AdapterNode n = this.child(i);
if (child.domNode == n.domNode) return i;
return -1; // Should never get here.
public AdapterNode child(int searchIndex) {
//Note: JTree index is zero-based.
org.w3c.dom.Node node =
domNode.getChildNodes().item(searchIndex);
return new AdapterNode(node);
public int childCount() {
return domNode.getChildNodes().getLength();
// This adapter converts the current Document (a DOM) into
// a JTree model.
public class DomToTreeModelAdapter
implements javax.swing.tree.TreeModel
// Basic TreeModel operations
public Object getRoot() {
//System.err.println("Returning root: " +document);
return new AdapterNode(document);
public boolean isLeaf(Object aNode) {
// Determines whether the icon shows up to the left.
// Return true for any node with no children
AdapterNode node = (AdapterNode) aNode;
if (node.childCount() > 0) return false;
return true;
public int getChildCount(Object parent) {
AdapterNode node = (AdapterNode) parent;
return node.childCount();
public Object getChild(Object parent, int index) {
AdapterNode node = (AdapterNode) parent;
return node.child(index);
public int getIndexOfChild(Object parent, Object child) {
AdapterNode node = (AdapterNode) parent;
return node.index((AdapterNode) child);
public void valueForPathChanged(TreePath path, Object newValue) {
// Null. We won't be making changes in the GUI
// If we did, we would ensure the new value was really new,
// adjust the model, and then fire a TreeNodesChanged event.
* Use these methods to add and remove event listeners.
* (Needed to satisfy TreeModel interface, but not used.)
private Vector listenerList = new Vector();
public void addTreeModelListener(TreeModelListener listener) {
if ( listener != null
&& ! listenerList.contains( listener ) ) {
listenerList.addElement( listener );
public void removeTreeModelListener(TreeModelListener listener) {
if ( listener != null ) {
listenerList.removeElement( listener );
// Note: Since XML works with 1.1, this example uses Vector.
// If coding for 1.2 or later, though, I'd use this instead:
// private List listenerList = new LinkedList();
// The operations on the List are then add(), remove() and
// iteration, via:
// Iterator it = listenerList.iterator();
// while ( it.hasNext() ) {
// TreeModelListener listener = (TreeModelListener) it.next();
* Invoke these methods to inform listeners of changes.
* (Not needed for this example.)
* Methods taken from TreeModelSupport class described at
* http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
* That architecture (produced by Tom Santos and Steve Wilson)
* is more elegant. I just hacked 'em in here so they are
* immediately at hand.
public void fireTreeNodesChanged( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesChanged( e );
public void fireTreeNodesInserted( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesInserted( e );
public void fireTreeNodesRemoved( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesRemoved( e );
public void fireTreeStructureChanged( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeStructureChanged( e );
}DocumentBuilderFactory can be configured to ignore white space.
http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setIgnoringElementContentWhitespace(boolean) -
How to Remove a Node from JTree?
I want to remove a node from a JTree but the node may or maynot be visible.
My method takes a String which is the name of the node.
The nodes im using are DefaultMutableTreeNode
This is my code so far but it doesnt work.
public void removePerson(String pName)
TreePath node = tree.getNextMatch(pName,0,Position.Bias.Forward);
tree.expandPath(node);
tree.removeSelectionPath(node);
}Any Suggestions or ways which i could achive this?
Thank you,I don't think removeSelectionPath is what you want to use.
These should help:
[http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)|http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)]
[http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml|http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml] -
How can I remove child node from JTree???
Hi,
I would like to remove all the child node of my jtree. For instance I would like to remove the c, d, and e nodes. It's possible to remove all the child node or to remove by her name ("c", "d", and "e"). If yes what is the method that it permit to do.
A-----
|
b-------c
|
|--------d
|
---------e
I use the model : DefaultMutableTreeNode
ThanksThere are a couple of ways it can be done. If your tree uses DefaultTreeModel as its TreeModel, you can use removeNodeFromParent(). This will remove the node from its parent and effectively remove its children, too. All nodes removed will be garbage-collected if there are no other references to them.
If your tree model is not the default tree model, but still uses MutableTreeNode, you can use either remove() or removeFromParent() on the node itself, depending on whether you want to remove the node itself or one of its children.
On the other hand, your tree may use a model that simply "mirrors" another data structure, in which case you would have to remove the node from the other data structure and have it reflected in the model. -
Dynamiclly remove node from JTree
hi all,
I want to remove nodes from a tree dynamically. I used "treeModel.removeNodeFromParent(node);". The node was removed from that treeModel, but the tree never updated. I tried to use tree.repaint() method. It doesn't work. Any suggestion?
thanks a lot in advance.try with TreeModel.reload(); This will surely work
-
Selectable JTable as leaf node in JTree
I've created a TreeCellRenderer that renders a JTable for nodes of type TableNode. The actual rendering seems to work fine, but the problem is that I am unable to select the rows in the JTable. I tried using a JTable-based TreeCellEditor, but that wasn't what I needed either. I don't need to edit the data, but only select an individual row so I can get its data to display in another panel on the screen.
Any ideas?
private class TableTreeCellRenderer extends DefaultTreeCellRenderer {
private JTable table = new JTable();
private DefaultTableModel model = (DefaultTableModel) table.getModel();
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
if (value instanceof TableNode) {
TableNode node = (TableNode) value;
model.setDataVector(node.getData(), node.getHeaders());
JScrollPane js = new JScrollPane(table);
js.setPreferredSize(getTableSize(table));
return js;
return super.getTreeCellRendererComponent(tree,
value,
selected,
expanded,
leaf,
row,
hasFocus);
private Dimension getTableSize(JTable table) {
return null;
}A renderer isn't a component which is added to a parent (tree in this case). It is only used for display purposes. You might try a [url http://java.sun.com/products/jfc/tsc/articles/treetable1/index.html]TreeTable.
-
Delete a node from JTree using removeSelectionPath question
hi guys,
how do i delete a node using removeSelectionPath?
jtree.removeSelectionPath(treePath);
it dont seem to work
cheersEach of that type of learning interactions has a minimum and a maximum number of buttons (nodes). For the circle matrix I found a minimum of 5 (central + one ring). When you select one of the buttons you should see a minus sign that allows to delete a button.
-
Populate a canvas when a tree-leaf node is clicked
I'm trying to populate a canvas or a list container with
images when a tree-leaf node is clicked. I got the tree control
working alright so far (populated via an external XML) but I'm
having a hard time figuring out how to populate the adjacent
container when a leaf node from a tree is clicked by a user. I know
I'm supposed to code this in the 'change' event but am having a
difficult time trying to figure out how to do this. I looked at the
source code in some of the sample apps but I couldn't find anything
that resemble what I'm trying to do.
Since each leaf node would be unique, each one of them would
trigger an external load of images (via http service) ... and so
the url would be unique as well for each.
'Appreciate the help from anyone who could help.
Thanks.Thanks for the quick response Tracy ...
Actually, I don't have mage load part coded yet :) ... I do
have a somewhat general idea on how it should be coded though (i
think, hehe). I'm thinking the selected item in the leaf node would
have the data for the 'url' or 'folder location' of the images that
would have to be retrieved and displayed in the canvas. I'm just
not sure how to go about diplaying them in the canvas. Do I have to
load them in some sort of array first and then datasourced it for
my canvas? Not really sure how to go about doing it ... 'am totally
newbie with Flex and just learning it by going through the online
help and looking at the codes on some of the sample apps.
Thanks again.
pixelflip -
How to dislay a frame when i clck on the node or leaf on the JTree
Hi All,
Iam doing project on swing. In that iam doing with JTree. The Jtree is displaying on the left side of the splitpane .My problem is if i click on the nodes or leaf in the JTree one panel should be open in on the right side of the spltpane. Iam pasting the code.please can any body knows the solution please send me.
regards
sonali
import java.awt.*;
import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.tree.*;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.net.URL;
import javax.swing.*;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JFrame;
import Test.Test1;
public class JFrame1 extends javax.swing.JFrame {
JScrollPane sp;
JPanel topPanel;
JPanel leftPanel;
JPanel bottomPanel;
JPanel rightPanel;
Border b ;
JTree tree;
DefaultTreeModel treeModel;
public JFrame1(){
getContentPane().setLayout(null);
setSize(405,305);
setVisible(false);
JPanel1.setLayout(null);
getContentPane().add(JPanel1);
JPanel1.setLayout(new GridLayout(1, 1));
JPanel1.setBounds(0,0,405,305);
JPanel1.add(JSplitPane1);
JSplitPane1.setBounds(0,5,405,305);
JSplitPane1.setContinuousLayout(false);
topPanel = new JPanel();
leftPanel = new JPanel();
bottomPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
leftPanel.setLayout(null);
b = new EtchedBorder();
leftPanel.setBorder(b);
leftPanel.setBounds(0,0,300,305);
bottomPanel.setLayout(new FlowLayout());
rightPanel = new JPanel();
rightPanel.setBounds(108, 0, 300, 305);
JSplitPane1.setRightComponent(rightPanel);
JSplitPane1.setLeftComponent(leftPanel);
rightPanel.setLayout(null);
topPanel.setBounds(0,0,305,25);
b = new EtchedBorder(0);
topPanel.setBorder(b);
bottomPanel.setBounds(0,26,300,280);
b = new BevelBorder(1, Color.black,Color.black);
bottomPanel.setBorder(b);
rightPanel.add(topPanel);
rightPanel.add(bottomPanel);
JSplitPane1.setDividerLocation(120);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
DefaultMutableTreeNode leaf3 = new DefaultMutableTreeNode("Leaf 3");
DefaultMutableTreeNode subroot1 = new DefaultMutableTreeNode("SubRoot1");
DefaultMutableTreeNode leaf11 = new DefaultMutableTreeNode("Leaf 11");
DefaultMutableTreeNode leaf21 = new DefaultMutableTreeNode("Leaf 21");
DefaultMutableTreeNode leaf31 = new DefaultMutableTreeNode("Leaf 31 skfjdsf sfjfdsl fslfkjdsfl sflkjaflksdfdslfjds lfsdlkfjdslk sdsdlkfjdsla fflkdasjfdslkjal");
DefaultMutableTreeNode subroot2 = new DefaultMutableTreeNode("SubRoot2");
DefaultMutableTreeNode leaf12 = new DefaultMutableTreeNode("Leaf 12");
DefaultMutableTreeNode leaf22 = new DefaultMutableTreeNode("Leaf 22");
DefaultMutableTreeNode leaf32 = new DefaultMutableTreeNode("Leaf 32");
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
treeModel.insertNodeInto(subroot, root, 0);
treeModel.insertNodeInto(leaf1, subroot, 0);
treeModel.insertNodeInto(leaf2, root, 1);
treeModel.insertNodeInto(leaf3, root, 2);
treeModel.insertNodeInto(subroot1, root, 3);
treeModel.insertNodeInto(leaf11, subroot1, 0);
treeModel.insertNodeInto(leaf21, subroot1, 1);
treeModel.insertNodeInto(leaf31, subroot1, 2);
treeModel.insertNodeInto(subroot2, root, 3);
treeModel.insertNodeInto(leaf12, subroot2, 0);
treeModel.insertNodeInto(leaf22, subroot2, 1);
treeModel.insertNodeInto(leaf32, subroot2, 2);
sp = new JScrollPane();
sp.setBounds(0,0,300,305);
sp.getViewport().add(tree);
sp.setViewportBorder(BorderFactory.createRaisedBevelBorder());
leftPanel.add(sp,BorderLayout.CENTER);
// SymPropertyChange lSymPropertyChange = new SymPropertyChange();
// JSplitPane1.addPropertyChangeListener(lSymPropertyChange);
SymWindow aSymWindow = new SymWindow();
this.addWindowListener(aSymWindow);
SymComponent aSymComponent = new SymComponent();
this.addComponentListener(aSymComponent);
public JFrame1(String sTitle)
this();
setTitle(sTitle);
public void setVisible(boolean b)
if (b)
setLocation(50, 50);
super.setVisible(b);
static public void main(String args[])
(new JFrame1()).setVisible(true);
public void addNotify()
Dimension size = getSize();
super.addNotify();
if (frameSizeAdjusted)
return;
frameSizeAdjusted = false;
Insets insets = getInsets();
javax.swing.JMenuBar menuBar = getRootPane().getJMenuBar();
int menuBarHeight = 0;
if (menuBar != null)
menuBarHeight = menuBar.getPreferredSize().height;
setSize(insets.left + insets.right + size.width, insets.top + insets.bottom + size.height + menuBarHeight);
boolean frameSizeAdjusted = false;
javax.swing.JPanel JPanel1 = new javax.swing.JPanel();
javax.swing.JSplitPane JSplitPane1 = new javax.swing.JSplitPane();
/*class SymPropertyChange implements java.beans.PropertyChangeListener{
public void propertyChange(java.beans.PropertyChangeEvent event){
Object object = event.getSource();
if (object == JSplitPane1)
JSplitPane1_propertyChange(event);
/* void JSplitPane1_propertyChange(java.beans.PropertyChangeEvent event){
System.out.println("!");
sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
sp.repaint();
tree.repaint();
class SymWindow extends java.awt.event.WindowAdapter{
public void windowActivated(java.awt.event.WindowEvent event){
Object object = event.getSource();
if (object == JFrame1.this)
JFrame1_windowActivated(event);
public void windowIconified(java.awt.event.WindowEvent event){
Object object = event.getSource();
if (object == JFrame1.this)
JFrame1_windowIconified(event);
void JFrame1_windowIconified(java.awt.event.WindowEvent event){
void JFrame1_windowActivated(java.awt.event.WindowEvent event){
class SymComponent extends java.awt.event.ComponentAdapter{
public void componentShown(java.awt.event.ComponentEvent event){
Object object = event.getSource();
if (object == JFrame1.this)
JFrame1_componentShown(event);
public void componentResized(java.awt.event.ComponentEvent event){
Object object = event.getSource();
if (object == JFrame1.this)
JFrame1_componentResized(event);
void JFrame1_componentResized(java.awt.event.ComponentEvent event){
System.out.println("!!");
JPanel1.setSize(this.getContentPane().getMaximumSize());
JSplitPane1.setSize((int)JPanel1.getMaximumSize().getWidth()-5,(int)JPanel1.getMaximumSize().getHeight()-5 );
topPanel.setBounds(0, 0, rightPanel.getWidth()-3, 25);
bottomPanel.setBounds(0,26,rightPanel.getWidth()-3,rightPanel.getHeight()-28);
sp.setSize((int)leftPanel.getMaximumSize().getWidth(),(int)leftPanel.getMaximumSize().getHeight());
sp.setAutoscrolls(true);
//sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
sp.repaint();
//sp.setSize((int)leftPanel.getSize().getWidth(),(int)leftPanel.getSize().getHeight() );
void JFrame1_componentShown(java.awt.event.ComponentEvent event){
System.out.println("!!!");
JPanel1.setSize(this.getContentPane().getMaximumSize());
JSplitPane1.setSize((int)JPanel1.getMaximumSize().getWidth()-5,(int)JPanel1.getMaximumSize().getHeight()-5 );
topPanel.setBounds(0, 0, rightPanel.getWidth()-3, 25);
sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
sp.repaint();
bottomPanel.setBounds(0,26,rightPanel.getWidth()-3,rightPanel.getHeight()-28);
}hi sculz,
i develped the tree, and tree selection listener also the 4 th point i didnt able to do . here is the code belo what i did.
iam not able to add the JSplit pane also.
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class Tree08 extends JFrame{
Hashtable theHashtable = new Hashtable();
int frameWidth = 300;
int frameHeight = 305;
int numberRows = 19;
JTree tree;
JPanel treePanel;
String plafClassName =
"com.sun.java.swing.plaf.motif.MotifLookAndFeel";
For future reference, the three plaf implementations
are:
com.sun.java.swing.plaf.metal.MetalLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
JLabel display;
public static void main(String args[]) {
new Tree08();
public Tree08 () {
theHashtable.put("Cabbage","Good in slaw");
theHashtable.put("Squash","The yellow variety");
theHashtable.put("Onion","Not too hot");
theHashtable.put("Squirrel","Likes to store nuts");
theHashtable.put("Rabbit","Runs fast");
theHashtable.put("Fox","Crazy like a ...");
theHashtable.put("Horse","Fun to ride");
theHashtable.put("Pig","Lives in mud");
theHashtable.put("Cow","Gives us milk");
theHashtable.put("Peach","From Georgia");
theHashtable.put("Grape","Saueeze into wine");
theHashtable.put("Apple","Red delicious");
theHashtable.put("Orange","Very juicy");
DefaultMutableTreeNode[] theTreeNodes = new
DefaultMutableTreeNode[numberRows];
theTreeNodes[0] = new DefaultMutableTreeNode("Sample
Tree");
theTreeNodes[1] = new
DefaultMutableTreeNode("Vegetables");
theTreeNodes[2] = new
DefaultMutableTreeNode("Cabbage");
theTreeNodes[3] = new
DefaultMutableTreeNode("Squash");
theTreeNodes[4] = new
DefaultMutableTreeNode("Onion");
theTreeNodes[5] = new
DefaultMutableTreeNode("Animals");
theTreeNodes[6] = new
DefaultMutableTreeNode("Forrest");
theTreeNodes[7] = new
DefaultMutableTreeNode("Squirrel");
theTreeNodes[8] = new
DefaultMutableTreeNode("Rabbit");
theTreeNodes[9] = new DefaultMutableTreeNode("Fox");
theTreeNodes[10] = new
DefaultMutableTreeNode("Farm");
theTreeNodes[11] = new
DefaultMutableTreeNode("Horse");
theTreeNodes[12] = new DefaultMutableTreeNode("Pig");
theTreeNodes[13] = new DefaultMutableTreeNode("Cow");
theTreeNodes[14] = new
DefaultMutableTreeNode("Fruit");
theTreeNodes[15] = new
DefaultMutableTreeNode("Peach");
theTreeNodes[16] = new
DefaultMutableTreeNode("Grape");
theTreeNodes[17] = new
DefaultMutableTreeNode("Apple");
theTreeNodes[18] = new
DefaultMutableTreeNode("Orange");
theTreeNodes[0].add(theTreeNodes[1]);
theTreeNodes[1].add(theTreeNodes[2]);
theTreeNodes[1].add(theTreeNodes[3]);
theTreeNodes[1].add(theTreeNodes[4]);
theTreeNodes[0].add(theTreeNodes[5]);
theTreeNodes[5].add(theTreeNodes[6]);
theTreeNodes[6].add(theTreeNodes[7]);
theTreeNodes[6].add(theTreeNodes[8]);
theTreeNodes[6].add(theTreeNodes[9]);
theTreeNodes[5].add(theTreeNodes[10]);
theTreeNodes[10].add(theTreeNodes[11]);
theTreeNodes[10].add(theTreeNodes[12]);
theTreeNodes[10].add(theTreeNodes[13]);
theTreeNodes[0].add(theTreeNodes[14]);
theTreeNodes[14].add(theTreeNodes[15]);
theTreeNodes[14].add(theTreeNodes[16]);
theTreeNodes[14].add(theTreeNodes[17]);
theTreeNodes[14].add(theTreeNodes[18]);
treePanel = new TreePanel(theTreeNodes[0]);
tree.addTreeSelectionListener(new MyTreeListener());
Container content = getContentPane();
content.add(treePanel,BorderLayout.CENTER);
display = new JLabel("Display Selection Here");
content.add(display,BorderLayout.SOUTH);
setSize(frameWidth, frameHeight);
setTitle("Copyright 1998, R.G.Baldwin");
setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);}
class MyTreeListener implements TreeSelectionListener{
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode theNode =
(DefaultMutableTreeNode)
(e.getPath().getLastPathComponent());
if (theNode.isLeaf()) {
display.setText((String)theHashtable.get(
theNode.getUserObject()));
class TreePanel extends JPanel {
public TreePanel(TreeNode root){
setLayout(new BorderLayout());
tree = new JTree(root);
JScrollPane sp = new JScrollPane(tree);
add(sp, BorderLayout.CENTER);
try{
UIManager.setLookAndFeel(plafClassName);
}catch(Exception ex){System.out.println(ex);}
SwingUtilities.updateComponentTreeUI(this);
for(int cnt = 0; cnt < numberRows; cnt++){
tree.expandRow(cnt);
regards
sonali -
Hiding / Filtering nodes in a JTree
I'm not exactly sure how to temporarily hide or filter nodes from a JTree. My scenario is described below.
I have a radio button group. If the first radio button is selected, all nodes are displayed. If the second button is selected, certain nodes are hidden.
Here is my attempt to filter nodes. I get the following excpetion when I try to filter nodes:
java.lang.NullPointerException: Null child not allowed
I assume this is coming from the getChild() method. I don't know what else to return besides null if I'm trying to filter the node out.
Can anyone provide some help or insight?
Thanks
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
public class MyTreeModel extends DefaultTreeModel
* Constructor.
* @param rootNode The root node.
public MyTreeModel( DefaultMutableTreeNode rootNode )
super( rootNode );
* Gets the child node.
* @param parent The parent node.
* @param index The index this child node resides in.
* @return The child node.
public Object getChild( Object parent, int index )
Object child = super.getChild( parent, index );
if ( RadioBtn.hideNodes() )
DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) child;
MyNode eNode = ( MyNode ) dmtn.getUserObject();
if ( !eNode.hasPermission() )
child = null; // "hide" the node
return child;
* Gets the index of a child.
* @param parent The parent node.
* @param child The child node.
* @return The index of the child node.
public int getIndexOfChild( Object parent, Object child )
int index = super.getIndexOfChild( parent, child );
if ( RadioBtn.hideNodes() )
DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
MyNode eNode = ( MyNode ) dmtn.getUserObject();
if ( !eNode.hasPermission() )
index = -1;
return index;
* Returns the number of children attached to the parent node.
* @param parent The parent node.
* @return The number of children of the parent node.
public int getChildCount( Object parent )
int numChildren = super.getChildCount( parent );
if ( RadioBtn.hideNodes() )
int counter = 0;
DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
// Loop through children and keep a count of all children nodes that should stay
for ( int x = 0; x < numChildren; x++ )
DefaultMutableTreeNode childDmtn = ( DefaultMutableTreeNode ) dmtn.getChildAt( x );
MyNode eNode = ( MyNode ) childDmtn.getUserObject();
if ( eNode.hasPermission() )
counter++;
numChildren = counter;
System.out.println( "Number of children in " + ( DefaultMutableTreeNode ) parent + ": " + numChildren );
return numChildren;
* Used from radio buttons to toggle hidden folders on and off.
public void triggerMe()
reload();Here it is optimized, for anyone who may need the code down the road.
public Object getChild( Object parent, int index )
Object child = super.getChild( parent, index );
if ( RadioBtn.isHidden() ) // If we should remove the 'special' nodes
DefaultMutableTreeNode dParent = ( DefaultMutableTreeNode ) parent;
int count = 0;
// Loop through children
for ( int x = 0; x < dParent.getChildCount(); x++ )
DefaultMutableTreeNode dChild = ( DefaultMutableTreeNode ) dParent.getChildAt( x );
MyNode eNode = ( MyNode ) dChild.getUserObject();
if ( eNode.hasPermission() )
// If it is the "xth" visible node, break the loop and set this object as the Child node
if ( count == index )
child = dChild;
break;
count++;
return child;
} -
Deleting Nodes from XML Tree (JTree)
I have created a XML Tree(extended from JTree) using XNodes ( extended from DefaultMutableTreeNode)
After some insertions, i need to delete certain nodes from the XML Tree.. but after deletion, XNode will be null.
subroutine is as follows...
appreciates any advice
Thanx
private XNode RemoveExtraNode( XNode xNode ){
int child;
String nodeType;
XNode childNode=null;
if ( (child=xNode.getChildCount() ) > 0){
for(int i=0;i<child;i++){
childNode=(XNode)xNode.getChildAt(i);
nodeType = childNode.getType();
if(nodeType.equals("DTD") )
childNode.removeFromParent();
}//end for (int i=1;i<child;i++)
}//endif((child=xNode.getChildCount())!=0)
return xNode;
}//RemoveExtraNodeHi IKEDA
Thanx for the reply.
I have tried xNode.remove(childNode) b4 and it still return a null JTree.
Anyway fyi i discover i can delete last child of xNode and return the correct java tree. therefore to delete a node of my choice i simply insert its next sibling nodes in its place and delete that particular node when it becomes the last child. -
Identifying leaf node in a JTree
I have a single selection JTree which was constructed using DefaultTreeModel.
asksAllowsChildren is set to 'true' in the tree model.
The nodes in the model are constructed using DefaultMutableTreeNode and each
node is marked if it allows children or not.
How can I find if a selection is a leaf node or not.
Thanks.Answering my own post, solution is:
tree.getModel().isLeaf(tree.getSelectionPath().getLastPathComponent())
where tree is the JTree object. -
How to remove all nodes (except root node)from a Jtree?
How to remove all nodes (except the root node)from a Jtree?
Either:
- remove all children of root.
- save the root node, throws away the tree model, build a new TreeModel with the saved root, set the new TreeModel in the JTree.
- implement your own TreeModel, which would support an emptyExceptRoot() method.
IMHO, using the DefautlTreeModel and DefaultMutableTreeNode does lead to all sorts of small problems when the app evolves, and implementing your own TreeNode and TreeModel is not that hard and much more efficient.
Maybe you are looking for
-
When I export a Quiktime file from Final Cut Pro 7, why do I get a mosaic effect on the edges of camera or subject movement (like blurred lines while the movement is happening in the clip)? Is there an export setting or sequence setting I am missing?
-
Is there any third party application email clients or settings to increase the attachment upload and download for the E7? Solved! Go to Solution.
-
Why does this cause error (ORA 01008: Not all variables bound)
When I assign values to parameters for a command object, I used the following code with the .NET provider: If oReq.CritSpec = Nothing Or oReq.CritSpec = "" Then cmdReq.Parameters.Add(":po5", DBNull.Value) Else cmdReq.Parameters.Add(":po5", oReq.CritS
-
Can any please tell me how to convert to soap to xsd.
-
Hello all! I was trying to download a jpg file to another site (forum) The site will not take it and sends a message back that I am missing a security token? Does anyone know what I should do?