JTree refresh
Hi!!!
I'm trying to implement JTree with TreeModel that sores the data in Document (as a result of XML parsing). I want to be able to refresh the tree when the data is changed.
I read in some tutorials that to do it I shoul implement in TreeModel functions like fireTreeNodeInserted(Node parent, Node child), fireTreeNodeChanged , etc.
But I can't understand what the implementation of those functions should be like?
Please ,help me :)
Yana.
In addition to es5f2000's advice (which is good), I also suggest you take a look at the API for the TreeModelListener interface:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/event/TreeModelListener.html
It describes what kind of events your TreeModel should fire, and when it should do it.
Similar Messages
-
JTree refresh probleme help me please
a can't reload my JTree from my server
my Jtree code:
user.add("Zeus@mxf");
user.add("Neptune@toto");
user.add("Ulysse@mars");
root =new DefaultMutableTreeNode("users");
for(int i=1; i<user.size(); i++)
userNode = new DefaultMutableTreeNode
(user.elementAt(i) );
root.add(userNode);
renderer.setOpenIcon(OpenIcon);
renderer.setClosedIcon(ClosedIcon);
renderer.setLeafIcon(PrinterIcon);
tree=new JTree(root);
tree.setCellRenderer(renderer);
and if a have receive the write data i do my refresh methode:
refresh()
userNode = new DefaultMutableTreeNode(user.elementAt(0) );
root.add(userNode);
((DefaultTreeModel)tree.getModel()).reload();
tree.treeDidChange();
tree.setCellRenderer(renderer);
tree.setLargeModel(true);
tree.repaint();
tree.revalidate();
why it dose not work ?????Sorry I have not ready examples, try to implement a method this way:
String newUser = user.elementAt(0);
public void addNode(String newUser){
DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(newUser);
root.add(userNode);
tree.getModel().nodeChanged((TreeNode)tree.getModel().getRoot());
tree.treeDidChange(); -
The Great JTree Refreshing Problem!
hi, i am using a Jtree to display information retrieved from an X.500 directory.
I am dealing with a great amount of information, and performance is the great issue in here. So, my problem is that, retrieving 3000 entries from the directory with JNDI takes 1 second,building and inserting the 3000 nodes takes 3 seconds, and in the end, the refresh of the jtree takes 7 seconds!!!!!
It's just to mutch time... i've tried dividing the 3000 entries in sets of 100 and insert this sets one at the time, so the JTree could refresh itself, this way, the user would see some action hapenning and it would be a lot more happy than he is now... The problem is that, the Jtree do not makes this refresh, only when a insert all, she starts to refresh and takes the infamous 7 seconds.
does this have anything to do with the low priority of the Swing threads that makes the refreshment...
please... any help is welcome
thanks in advanceuse DefaultMutableTreeNode's insert/add methods to add
the node.
Steps:
- make the root node.
- insert the nodes in the root node,
- set the root node as the root to the treemodel.
it may be useful to u.A little off the subject of the original question, but when I want to use the same JTree to display new information (instead of popping up a new frame with the new info), I also create a new root node, populate it, and then set the currently-displayed JTree's model's root to the new root node. However it never redraws with the new tree contents, even though I call invalidate() on the JTree.
What explicitly do you do to have it redraw with the new contents?
Thanks!
Lloyd -
I use a JTree for displaying a custom TreeModel based on a DOM document. I have a problem with refreshing the tree: the tree refreshes itself correctly when it has focus, and does nothing when it has not (at least it seems to be related to focus), even though TreeModelEvents are fired. I know the problem originates from the custom TreeModel (others work fine), but I can't find what's wrong. I compared it to the DefaultTreeModel source and found nothing interesting.
In addition to that, the tree is displayed without its vertical connecting lines (but someone told me its a symptom of bad refreshing).
Anyone has an idea? Thanks in advance.
SimonI faced the same problem. Try adding a TreeModelListener and updateUI in it . . .
yourTreeModel.addTreeModelListener(new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) {}
public void treeNodesInserted(TreeModelEvent e) {
yourTree.updateUI();
public void treeNodesRemoved(TreeModelEvent e) {
yourTree.updateUI();
public void treeStructureChanged(TreeModelEvent e) {}
}); -
JTree refresh without collapsing my nodes
Hello,
I have a JTree using a custom TreeModel. I've also extended the TreeNode.
What is the most elegant method to refresh the tree or only a node without
collapsing the currently expanded nodes?
Please note that there are multiple types of TreeNodes each representing
a different object to display in the tree and contains an object that represents its
value. Also the node has a method createChildren() to determine and create
the child TreeNodes. Children are loaded from a business delegate. I need the
tree to re-query the model (maybe for only one node) about the data and redisplay
the changes without affecting the collapsed/expanded state of the nodes that
are not changed (not supposed to refresh).
My model actually asks the node for data like getChildsCount(), isLeaf() etc, etc.
I'd like to say:
myCustomNodeInstance.refresh();
or
myCustomTreeModelInstance.refresh(myCustomNodeInstance);
and all nodes that are not children of myCustomNodeInstance to preserve
their state.
ThanxDid you try to call repaint() method on JTree ?
-
Save me!! about JTree refresh!!
Hello ereryone. I met a problem and I tried lots of method,such as reload(),validate(),revalidate(),but it seemed that they doesn't work.
My gui is about: here is a JSplitpane,on the left part ,there is a panel(borderlayou) in it. A button in the panel's west and a JScrollPane in the panel's center. A JTree component in the JScrollPane.
The wished fountion is when the program run, the tree would show the demanded disk file system(read config file to get the root file).when u click the button, a JFilechooser come out and u can choose another dir of the disk. when u click "ok", the tree should show the new file structure of the new dir.
here are 2 java file.
//myclass.java
//myclass.java
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import javax.swing.ImageIcon;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class myclass extends JFrame implements WindowListener{
private JFrame f=null;
private JLabel labeladdress;
private JLabel labelstatus;
private JTree tree;
private JSplitPane splitPane;
private JEditorPane htmlPane;
private JPopupMenu Popup=null;
private DefaultTreeModel treeModel=null;
private String str="";
private boolean statusbarflag=true;
private boolean addressbarflag=true;
String currentpos;
ImageIcon icon=new ImageIcon("icons/paste.gif");
ReadAndWriteXML wp=new ReadAndWriteXML();
public WebPageSave(Vector vec) throws FileNotFoundException, SecurityException,Exception{
wp.address_Vector=new Vector();
wp.readXMLFile("sys/workposition.xml");
f=new JFrame("WebHunter");
Container contentPane=(JPanel)f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel panel=new JPanel();
panel.setLayout(new BorderLayout());
paneln.setLayout(new BorderLayout());
contentPane.add(panel,BorderLayout.CENTER);
contentPane.add(paneln,BorderLayout.NORTH);
//添加JTree和JEditorPane
//JTree tree=new JTree();
initialtree(wp.address_Vector.get(0).toString());
final JScrollPane scrollPanel=new JScrollPane(tree);
final JPanel mainleft=new JPanel(new BorderLayout());
JButton jchange=new JButton("change position");
currentpos=wp.address_Vector.get(0).toString();
//the button anonymous class
jchange.addActionListener(new ActionListener(){ //change the dir
public void actionPerformed(ActionEvent event){
JFileChooser chooser=new JFileChooser(currentpos);
chooser.setDialogTitle("choose ur position");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result=chooser.showDialog(f,"ok");
if(result==JFileChooser.APPROVE_OPTION){
int i=JOptionPane.showConfirmDialog(f,"make sure?","notice",JOptionPane.YES_NO_OPTION);
if(i==JOptionPane.YES_OPTION){
try{
//ReadAndWriteXML wp=new ReadAndWriteXML();
wp.address_Vector=new Vector();
wp.readXMLFile("sys/workposition.xml");
FileOperation u=new FileOperation();
u.xcopy(wp.address_Vector.get(0).toString(),chooser.getSelectedFile().toString());
u.delete(new File(wp.address_Vector.get(0).toString()));
}catch(Exception e){
e.printStackTrace();
//write the new positon to the workposition.xml文件
try{
wp.writeXMLFile("sys/workposition.xml",chooser.getSelectedFile().toString());
}catch (Exception e) {
e.printStackTrace();
?????? //refresh tree
try{
ReadAndWriteXML wp=new ReadAndWriteXML();
wp.address_Vector=new Vector();
wp.readXMLFile("sys/workposition.xml");
currentpos=wp.address_Vector.get(0).toString();
//currentpos=chooser.getSelectedFile().toString();
//initialtree(wp.address_Vector.get(0).toString());
initialtree(chooser.getSelectedFile().toString());
//JScrollPane scrollPanel=new JScrollPane(tree);
//mainleft.add(scrollPanel,BorderLayout.CENTER);
//tree.
//mainleft.validate();
JOptionPane.showConfirmDialog(f,"change positon successfully!","notice",JOptionPane.CLOSED_OPTION);
}catch (Exception e1) {
e1.printStackTrace();
mainleft.add(scrollPanel,BorderLayout.CENTER);
mainleft.add(jchange,BorderLayout.SOUTH);
JScrollPane scrollPane2=new JScrollPane(htmlPane);
splitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,mainleft,scrollPane2);
splitPane.setDividerSize(10);
splitPane.setDividerLocation(180);
panel.add(splitPane,BorderLayout.CENTER);
panel.add(labelstatus,BorderLayout.SOUTH);
f.pack();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setExtendedState(Frame.MAXIMIZED_BOTH);
f.setIconImage(icon.getImage());
//f.setBounds(0,0,1020,725);
f.show();
//f.addWindowListener(new WindowListenerHandle());
f.addWindowListener(this);
}//constructor over!!!
public void initialtree(String s) throws FileNotFoundException,SecurityException,Exception{
//ReadAndWriteXML treefile=new ReadAndWriteXML();
//treefile.address_Vector=new Vector();
//treefile.readXMLFile("sys/workposition.xml");
//tree=new FileTree(s);
//tree.revalidate();
//((DefaultTreeModel)tree.getModel()).nodeStructureChanged((DefaultTreeModel)s);
tree=new showDir().initTree(s);
tree.revalidate();
//DefaultTreeModel model=new DefaultTreeModel(tree.getModel());
//treeModel=(DefaultTreeModel) tree.getModel();
//tree.setModel(model);
//treeModel.reload();
tree.setEditable(true);
//FileTree.java
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class FileTree extends JTree {
private static DefaultTreeModel model;
public FileTree(String path) throws FileNotFoundException, SecurityException {
super((TreeModel)null); // Create the JTree itself
// Use horizontal and vertical lines
putClientProperty("JTree.lineStyle", "Angled");
// Create the first node
FileTreeNode rootNode = new FileTreeNode(null, path);
model=new DefaultTreeModel(rootNode);
// Populate the root node with its subdirectories
boolean addedNodes = rootNode.populateDirectories(true);
//model.nodeStructureChanged(rootNode);
setModel(new DefaultTreeModel(rootNode));
//(new DefaultTreeModel(rootNode))this.getModel().reload();
//model.reload();
// Listen for Tree Selection Events
addTreeExpansionListener(new TreeExpansionHandler());
// Returns the full pathname for a path, or null if not a known path
public String getPathName(TreePath path) {
Object o = path.getLastPathComponent();
if (o instanceof FileTreeNode) {
return ((FileTreeNode)o).file.getAbsolutePath();
return null;
// Returns the File for a path, or null if not a known path
public File getFile(TreePath path) {
Object o = path.getLastPathComponent();
if (o instanceof FileTreeNode) {
return ((FileTreeNode)o).file;
return null;
// Inner class that represents a node in this file system tree
protected static class FileTreeNode extends DefaultMutableTreeNode {
public FileTreeNode(File parent, String name)
throws SecurityException, FileNotFoundException {
this.name = name;
// See if this node exists and whether it is a directory
file = new File(parent, name);
if (!file.exists()) {
throw new FileNotFoundException("File " + name + " does not exist");
isDir = file.isDirectory();
// Hold the File as the user object.
setUserObject(file);
// Override isLeaf to check whether this is a directory
public boolean isLeaf() {
return !isDir;
// Override getAllowsChildren to check whether this is a directory
public boolean getAllowsChildren() {
return !isDir;
// For display purposes, we return our own name
public String toString() {
return name;
// If we are a directory, scan our contents and populate
// with children. In addition, populate those children
// if the "descend" flag is true. We only descend once,
// to avoid recursing the whole subtree.
// Returns true if some nodes were added
boolean populateDirectories(boolean descend) {
boolean addedNodes = false;
// Do this only once
if (populated == false) {
if (interim == true) {
// We have had a quick look here before:
// remove the dummy node that we added last time
removeAllChildren();
interim = false;
String[] names = file.list(); // Get list of contents
// Process the directories
for (int i = 0; i < names.length; i++) {
String name = names;
File d = new File(file, name);
try {
FileTreeNode node = new FileTreeNode(file, name);
if (d.isDirectory()) {
//FileTreeNode node = new FileTreeNode(file, name);
this.add(node);
if (descend) {
node.populateDirectories(false);
addedNodes = true;
if (descend == false) {
// Only add one node if not descending
break;
else{
//FileTreeNode node = new FileTreeNode(file,name);
this.add((MutableTreeNode)node);
//model.reload();
//model.nodeStructureChanged(node);
//((DefaultTreeModel)parent.getModel()).nodeStructureChanged(node);
} catch (Throwable t) {
// Ignore phantoms or access problems
// If we were scanning to get all subdirectories,
// or if we found no subdirectories, there is no
// reason to look at this directory again, so
// set populated to true. Otherwise, we set interim
// so that we look again in the future if we need to
if (descend == true || addedNodes == false) {
populated = true;
} else {
// Just set interim state
interim = true;
return addedNodes;
protected File file; // File object for this node
protected String name; // Name of this node
protected boolean populated;// true if we have been populated
protected boolean interim; // true if we are in interim state
protected boolean isDir; // true if this is a directory
// Inner class that handles Tree Expansion Events
protected class TreeExpansionHandler implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent evt) {
TreePath path = evt.getPath(); // The expanded path
JTree tree = (JTree)evt.getSource(); // The tree
// Get the last component of the path and
// arrange to have it fully populated.
FileTreeNode node = (FileTreeNode)path.getLastPathComponent();
if (node.populateDirectories(true)) {
((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node);
public void treeCollapsed(TreeExpansionEvent evt) {
// Nothing to doThere is a method for reloading a tree
Have a look at this:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultTreeModel.html#reload(javax.swing.tree.TreeNode)
Hope I understood your problem and it helps. -
I am having trouble displaying a JTree with newly added nodes.
I have a JTree, inside a JPanel, JScrollPane and JSplitPane.
I create the JTree with a single root node which displays correctly.
I update the JTree with new children which displays correctly.
Using the same exact routine as above - I add additional new children to the root, the new children do not display in the JTree.
I have confirmed that I am using the correct tree and root node in debug that the tree/node objects has been correctly updated. It is just not displaying the new children to the root.
I can expand and collapse the tree which does not show the new children, just the original populated root.
After the root has been updated, I have tried a number of methods to resolve: tree/jpanel/jscrollpane/jsplitpane .revalidate, invalidate, repaint, etc.
I am using v1.4.1.
What am I missing here?
Thanks in advance.i use two classes fro add or insert nodes in a tree, one adds the node at the same level of the current selected node, and the other intert it inside:
// InsertaTreeConfAction.java
package ayto;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.tree.*;
public class InsertaTreeConfAction extends AbstractAction {
TreeConf treeConf;
MenuTreeConf menuPrincipal;
TreeConfAppAyto confNodo;
DefaultTreeModel model;
TreeTreeConf tree;
public InsertaTreeConfAction(TreeConf treeConf,String text) {
super(text);
this.treeConf = treeConf;
InitAction();
public InsertaTreeConfAction(TreeConf treeConf, String text, Icon icon) {
super(text, icon);
this.treeConf = treeConf;
InitAction();
public void InitAction(){
menuPrincipal = treeConf.getMenu();
confNodo = treeConf.selNodo;
model = treeConf.getTree().getMyModel();
tree = treeConf.getTree();
public void actionPerformed(ActionEvent ev) {
model = treeConf.getTree().getMyModel();
TreePath tp = tree.getSelectionPath( );
MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
int insertIndex = 0;
if (insertNode.getParent( ) != null) {
MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
//insertIndex = parent.getIndex(insertNode) + 1;
//insertNode = parent;
MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo Insertado"));
model.insertNodeInto(node, insertNode, insertIndex);
treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
treeConf.updater.update(); // esto no colapsa el arbol
treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);
// AnadeTreeConfAction.java
package ayto;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.tree.*;
public class AnadeTreeConfAction extends AbstractAction {
TreeConf treeConf;
MenuTreeConf menuPrincipal;
TreeConfAppAyto confNodo;
DefaultTreeModel model;
TreeTreeConf tree;
public AnadeTreeConfAction(TreeConf treeConf,String text) {
super(text);
this.treeConf = treeConf;
InitAction();
public AnadeTreeConfAction(TreeConf treeConf, String text, Icon icon) {
super(text, icon);
this.treeConf = treeConf;
InitAction();
public void InitAction(){
menuPrincipal = treeConf.getMenu();
confNodo = treeConf.selNodo;
model = treeConf.getTree().getMyModel();
tree = treeConf.getTree();
public void actionPerformed(ActionEvent ev) {
model = treeConf.getTree().getMyModel();
TreePath tp = tree.getSelectionPath( );
MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
int insertIndex = 0;
if (insertNode.getParent( ) != null) {
MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
insertIndex = parent.getIndex(insertNode) + 1;
insertNode = parent;
MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo A�adido"));
model.insertNodeInto(node, insertNode, insertIndex);
treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
treeConf.updater.update(); // esto no colapsa el arbol
treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct); -
Exception occured in JTree refresh
I have constructed a tree and when ever any change occured to the tree i am sending an event from server which will notify all the clients.
Then the tree is refreshed by using TreeModelEvent methods like nodeInserted, nodesRemoved, nodesModified etc.
The no of events generated are so many that if there are 20 nodes then for each second say for each node there will be 10 updates.
At this time i am getting exception saying
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:431)
at javax.swing.tree.DefaultMutableTreeNode.getChildAt(DefaultMutableTreeNode.java:230)
at javax.swing.tree.VariableHeightLayoutCache$VisibleTreeStateNodeEnumeration.updateNextIndex(VariableHeightLayoutCache.java:1739)
at javax.swing.tree.VariableHeightLayoutCache$VisibleTreeStateNodeEnumeration.updateNextObject(VariableHeightLayoutCache.java:1690)
at javax.swing.tree.VariableHeightLayoutCache$VisibleTreeStateNodeEnumeration.nextElement(VariableHeightLayoutCache.java:1681)
at javax.swing.plaf.basic.BasicTreeUI.paint(BasicTreeUI.java:1121)
at javax.swing.plaf.metal.MetalTreeUI.paint(MetalTreeUI.java:152)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:541)
at javax.swing.JComponent.paint(JComponent.java:808)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4787)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4740)
at javax.swing.JComponent._paintImmediately(JComponent.java:4685)
at javax.swing.JComponent.paintImmediately(JComponent.java:4488)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
This is a big problem for me and i have to fix it as early as possible.
Thanks in advanceHai ->some array index out of bound exception!???!!!????
Check the size of the array u r using- r u using any vector-check that area u may try to use more than what number of components in ths array.
Can you post a runnable code with similar problem!
so you can get your problem solved as early as possible! -
I want a method that takes a HashMap as an argument and builds a
tree(using JTree) from it.
NOTE: Each time I call the method,it should not create a new instance of DefaultTreeMode/JTree but use the one created once (when the constructor of the class containing the method is invoked once).In short,the previous nodes in DefaultTreeMode and JTree should be removed and the new tree must be built from the supplied HashMap.
public void rebuildTree(HashMap lastMap)
TreeMap newMap = new TreeMap(lastMap);
Set keySet = newMap.keySet();
it = keySet.iterator();
((DefaultTreeModel)tree.getModel()).setRoot(null);
tree.removeAll();
}I am having a screen which acts as a front end to add nodes to the tree.
The nodes get added as I want but when I try to move a node from one place to other(try to change its position in the tree),the tree doesn't get updated properly.
The functionality to move a node is to be acheived by the method I have written which gets a hashmap which has all the nodes... -
before i add a new node to a jtree some nodes r expanded. so after i added the new node in the JTree i want to show the nodes that were previously expanded in the jtree. what is the way?
I am using,
model : DefaultTreeModel
tree : JTree
rootnode : DefaultMutableTreeNode
Now i am calling the model.reload() method. if the user is selected any node in the tree then i add the new node and call the reload, cause the cast cast exception: can't to cast MyObject to TreeNode. why?Thank you very much Steve, I was able to integrate
your code in my own application. It's working fine.
I will do more tests with it and let you know about
it.That's terrific Andre. I am very pleased the code worked and helped you. I hope this solution 'nails' the much wondered about JTree refresh problem once and for all.
Should you come across any bugs, or if you think of any means of improvement during your testing, I would be very interested to hear from you.
In any case, good luck with your project, and all the best,
Steve -
Refreshing the jtree in a jpanel
hi,
i created a jtree of files in a certain folder... if some files changed in my folder, how can i refresh the jtree in my jpanel...
thanks!!!Hi,
look here:
http://forum.java.sun.com/thread.jspa?threadID=478780&messageID=2226565
L.P. -
Problem in refreshing JTree inside Jscrollpane on Button click
hi sir,
i have problem in refreshing JTree on Button click inside JscrollPane
Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
please help me.
import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test
public static void main(String[] args)
JFrame jf=new TestTreeRefresh();
jf.addWindowListener( new
WindowAdapter()
public void windowClosing(WindowEvent e )
System.exit(0);
jf.setVisible(true);
class TestTreeRefresh extends JFrame
DefaultMutableTreeNode top;
JTree tree;
JScrollPane treeView;
JPanel jp=new JPanel();
JButton jb= new JButton("Refresh");
TestTreeRefresh()
setTitle("TestTree");
setSize(500,500);
getContentPane().setLayout(null);
jp.setBounds(new Rectangle(1,1,490,490));
jp.setLayout(null);
top =new DefaultMutableTreeNode("The Java Series");
createNodes(top);
tree = new JTree(top);
treeView = new JScrollPane(tree);
treeView.setBounds(new Rectangle(50,50,200,200));
jb.setBounds(new Rectangle(50,300,100,50));
jb.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
jp.remove(treeView);
top =new DefaultMutableTreeNode("The Java ");
createNodes(top);
tree = new JTree(top);
treeView = new JScrollPane(tree);
treeView.setBounds(new Rectangle(50,50,200,200));
jp.add(treeView);
jp.repaint();
jp.add(jb);
jp.add(treeView);
getContentPane().add(jp);
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
category = new DefaultMutableTreeNode("Books for Java Programmers");
top.add(category);
book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
category.add(book);
book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
category.add(book);
book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
category.add(book);
book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
category.add(book);
book = new DefaultMutableTreeNode("The Java Programming Language");
category.add(book);
book = new DefaultMutableTreeNode("The Java Developers Almanac");
category.add(book);
category = new DefaultMutableTreeNode("Books for Java Implementers");
top.add(category);
book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
category.add(book);
book = new DefaultMutableTreeNode("The Java Language Specification");
category.add(book);
}hi sir ,
thaks for u'r suggession.Its working fine but the
properties of the previous tree were not working
after setModel() property .like action at leaf node
is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
If you still have a problem then please post some code (using the [code] tags of course). -
How can i refresh a jtree using DefaultMutableTreeNode?
I already create a jtree using DefaultMutableTreeNode, and i also could implement to it the addMouseListener to do a action when the user press every node......Also i used the following instruction to remove all nodes: root_tree.removeAllChildren(); and it instruction remove all the nodes....but when i :
fill the tree
compile my program
i see the tree in my jpanel....it is Ok!
now.....
fill the tree
remove the tree
compile my program
i see only the root (this i wish) it is Ok!
But now i would like that after that i press a combo element (in the actionperformed method):
remove the tree
fill the three with the new nodes
show the tree
But my tree always is the same :(......is like it to need a repaint ....but i already implement it...but i obtain the same result.....
Do somebody have any suggestion...or idea how i can do a refresh in my jtree?....
Anybody could help me please?
Thanks in advance.....
MaryConstruct your tree like this:DefaultMutableTreeNode rootNode = xxx;
DefaultTreeModel model = new DefaultTreeModel( rootNode );
JTree tree = new JTree( model );When you update the root node, just tell the model to fire the appropriate change event by doing this:model.reload( rootNode );or this:model.nodeStructureChanged( rootNode );or this:model.setRoot( rootNode ) -
JTree - changed content, refresh
Hello,
I have a problem in my program I can`t solve...
basically I am using drop-down menu with different drives (c:, d:, etc.). Don`t ask me why I don`t use the JTree to display all the drives, I simply need to display each drive separately.
when I select the drive, JTree pops up with the content of the drive.
Problem comes in, when the JTree is already displayed and I go into my drop-down menu to select a different drive.... Everything seems to work fine in background.... The tree gets build up, I just somehow cannot update (or refresh) the screen....
did anyone experienced similar problem?
thank you
OtakarNo, I am not using TreeModel.. Let me post the code... I am using 3 different files:
MainModule.java
DetectDrives.java
FileSystem.java
I think You might wanna see the ChoiceListener in MainModule
thank you for you time
MainModule.java
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.*;
public class MainModule{
private JFrame aFrame; // BASE frame
private JPanel driveListPane;
private JList driveList;
// MENU Bar Components
private JMenuBar aMenuBar;
private JMenu fileMenu, editMenu, viewMenu, settingsMenu, helpMenu;
private JMenuItem newMenuItem, openMenuItem, saveMenuItem, // FILE menu Items
saveAsMenuItem, exitMenuItem, //
selectDriveMenuItem, selectOutputMenuItem; // SETTINGS menu Items
// ComboBox
private JComboBox aComboBox;
// Buttons
private JButton selectDriveButton, printButton;
// Listeners
private PrintButtonListener prtListener;
private ChoiceListener choiceListener;
// Labels
private JLabel sourceLabel, label1, label2;
private int listRows;
public static String drive;
private DetectDrives dd;
private FileSystem fs;
private int ct;
/*============ CONSTRUCTOR ===========================================================\
|
public MainModule(){
ct = 0;
// create a MAIN WINDOW (Frame)
drive = new String("C:\\");
aFrame = new JFrame("Otax Drive Printer 0.99b");
aFrame.setSize(800, 600);
aFrame.setLocation(100, 50);
aFrame.getContentPane().setLayout(null);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the categories in a menu bar
aMenuBar = new JMenuBar();
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
viewMenu = new JMenu("View");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
// create menu items for FILE menu
newMenuItem = new JMenuItem("New", 'N');
openMenuItem = new JMenuItem( "Open", 'O');
saveMenuItem = new JMenuItem( "Save", 'S' );
saveAsMenuItem = new JMenuItem( "Save As", 'A');
exitMenuItem = new JMenuItem("Exit", 'E');
// create menu items for SETTINGS menu
selectDriveMenuItem = new JMenuItem("Select Drive", 'D');
selectOutputMenuItem = new JMenuItem("Select Output", 'O');
// detect drives mounted to system and put them into JComboBox
dd = new DetectDrives();
aComboBox = new JComboBox(dd.detectCdDrives());
aComboBox.setBounds(100, 5, 180, 20);
//create labels
sourceLabel = new JLabel("Select Source:");
sourceLabel.setBounds(6, 4, 90, 20);
label1 = new JLabel("Current Drive: ");
label1.setBounds(2, 500, 90, 20);
label2 = new JLabel();
label2.setBounds(85, 500, 50, 20);
//create buttons
printButton = new JButton("Print");
printButton.setBounds(2, 50, 101, 16);
//create Accelerators for FILE MenuItems
newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, InputEvent.CTRL_MASK, false));
//create the action listeners (listener definitions bellow)
prtListener = new PrintButtonListener();
choiceListener = new ChoiceListener();
//connect the action listeners with menu items
printButton.addActionListener(prtListener);
aComboBox.addActionListener(choiceListener);
// LISTENERS Definitions start HERE ====================================
public class PrintButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("print action performed: " + drive);
public class ChoiceListener implements ActionListener{
public void actionPerformed( ActionEvent e)
ct++;
System.out.println(ct + " event started");
String drive = new String(aComboBox.getSelectedItem().toString().substring(0,2));
label2.setText(drive);
fs = new FileSystem(drive + "//");
fs.sortFiles();
fs.addNodes(drive);
DefaultMutableTreeNode top = fs.getNodes();
JTree tree = new JTree(top);
tree.setBounds(10, 30, 500, 450);
aFrame.getContentPane().add(tree);
aFrame.repaint();
public void addComponents(){
aMenuBar.add(fileMenu); // create menu
aMenuBar.add(editMenu);
aMenuBar.add(settingsMenu);
aMenuBar.add(helpMenu);
fileMenu.add(newMenuItem); //add items to the FILE menu
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
fileMenu.add(saveMenuItem);
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
settingsMenu.add(selectDriveMenuItem);
settingsMenu.add(selectOutputMenuItem);
aFrame.setJMenuBar(aMenuBar);
aFrame.getContentPane().add(aComboBox);
aFrame.getContentPane().add(sourceLabel);
aFrame.getContentPane().add(label1);
aFrame.getContentPane().add(label2);
aFrame.setVisible(true);
public static void main(String [] args){
MainModule m1 = new MainModule();
m1.addComponents();
DetectDrives.java
import java.io.*;
import java.util.Vector;
import javax.swing.filechooser.*;
public class DetectDrives{
private FileSystemView fsv;
private File[] roots;
private Vector drives;
/*======== CONSTRUCTOR =====================================================================\
|Purpose: To INITIALIZE the object |
|Variables: (FileSystemView) fsv - creates the Object containing info about current system |
| (File[]) roots - array used to store all drives currently mounted to system |
| (Vector) drives - vector used for storage of selected info about drives |
\==========================================================================================*/
public DetectDrives(){
drives = new Vector(0,1); // *Create empty Vector(0) with expansion capacity (1)
//--- Get a FileSystemView object for the current system
fsv = FileSystemView.getFileSystemView();
//--- Get an array of File objects describing the 'roots' attached to the system
roots = File.listRoots();
/*SD1)==== Method detectCdDrives() ========================================================\
|Purpose: To SCAN the system for any drives mounted and add DRIVE LETTER and DRIVE NAME |
| to a Vector. It Also CHECKS if drive CONTAINS any DATA or if it`s EMPTY. |
|Variables: (int) i - a loop iterator |
| (String) cdInfo - temporary storage for drive information during drive check |
| (Vector) drives - storage for driveletter and drive name for all drives |
| This Vector is returned upon function call |
public Vector detectCdDrives(){
String cdInfo;
//SCAN system and RETRIEVE drives
for(int i = 0; i < roots.length; i++){
if((fsv.getSystemDisplayName(roots)).equals("")) //--FIND OUT if any DATA on DRIVE
cdInfo = fsv.getSystemTypeDescription(roots[i]) + " ";
else
cdInfo = fsv.getSystemDisplayName(roots[i]);
drives.addElement(roots[i].getPath() + " " + cdInfo.substring(0, cdInfo.length()-5));
return drives;
FileSystem.java
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.io.*;
import java.util.Vector;
public class FileSystem{
private String driveLetter;
private Vector root;
private Vector dirs;
private Vector files;
private File dir;
private File [] allFiles;
private DefaultMutableTreeNode top;
/*================= File System Constructor ================================\
|Purpose: To initialize the conject and to accept drive letter selected in |
| main module |
public FileSystem(String dl){
driveLetter = dl;
/*================= Method: sortFiles() ====================================\
|Purpose: To sort content of selected drive, directories (alphabetically), |
| followed by files (alphabeticaly) |
public void sortFiles(){
dir = new File (driveLetter);
allFiles = dir.listFiles();
root = new Vector(2,1);
dirs = new Vector(0,1);
files = new Vector(0,1);
//---- Separate Directories and Files into 2 different vectors
for(int i = 0; i < allFiles.length; i++){
if(allFiles.isDirectory())
dirs.add(allFiles[i]);
else
files.add(allFiles[i]);
//---- Add elements from dirs and files Vectors into root vector
for(int i = 0; i < dirs.size(); i++){
root.add(dirs.elementAt(i));
for(int i = 0; i < files.size(); i++){
root.add(files.elementAt(i));
/*================= Method: addNodes() =====================================\
|Purpose: to build the file structure which will be used to create the tree |
|Variables: drive = used to accept the drive letter representing the root |
| top = primary (root) node in the structure) |
| root = vector of all files in the drive |
public void addNodes(String drive){
top = new DefaultMutableTreeNode(drive);
DefaultMutableTreeNode node = null;
for(int i = 0; i < root.size(); i++){
node = new DefaultMutableTreeNode(root.elementAt(i));
top.add(node);
/*================= Method: getNodes() =====================================\
|Purpose: To return variable top, which holds the files structure and will |
| be used to build the tree |
public DefaultMutableTreeNode getNodes(){
return top; -
Hi,
Can anyone tell how to refresh a JTree(javax.swing.Jtree) used for displaying file system(both local and remote).
I'm getting a problem if a file/directoy is added to the file system, after my Applet is loaded. Actually, i have used DefaultTreeModel's reload() method and calling it inside SwingUtilities.invokeLater() using Thread, but its not working.
Plz help me out.
ThanksHi everybody,
CAN ANYONE HELP ME OUT?????????
Maybe you are looking for
-
ACS 5.3 to ISE 1.2 Migration
Hi Experts, Good Day! I really need help I already did some troubleshooting but the issue I'm encountering still exists. I am trying to migrate my ACS 5.3 to ISE 1.2 using the migration tool. I;m able to extract the data from ACS however, when I trie
-
Error 7 windows error 127 i want to fix
Error 7 windows error 127 i want to fix this asap
-
Trouble with SWF files in Keynote 3
I am working in Keynote for the first time and having trouble bringing in a .swf file. I am having to use a Windows XP box to build the flash file and then moving them over to a Mac to drop into Keynote. I have Keynote 3 and have QuickTime Version 7.
-
My Iphone 3g cannot detect wifi
my iphone 3g cannot detect wifi and the bluetooth is not working as well it can't detect bluetooth also... help me
-
Camera problem: photo bar changed place and automatically rotates horizontal
Hi everybody, I've searched the forum but I didn't find a similiar topic that describes my problem... After the update for Xperia 2.3.3 I'm having troubles with my camera. I CAN take photo's and video's but as soon as I've made a photo the miniature