Problems updating JTree changes with JButton - java

I'm on a project with several people, and my task is to compile a working JTree to show the structure of a set directory. As it is, the JTree shows the correct structure of files and folders when the class starts. However, I can't seem to get it to be able to update when files are added or subtracted (not with the JTree). In my happy ignorance (quite presistant that one) I added a JButton with;
treeModel.reload();
...and hoped that would do the trick. It reloaded the JTree sure enough, but didn't change the file structure, even though several files were added after the class loaded.
And it is thus I place my trust in this community to both point out the source of my issues, and other lackings in semantics and logic. I'm a willing learner.
public class FileTree extends JPanel {
private JTree tree;
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
public FileTree(JPanel jp) {
jp.setLayout(new BorderLayout());
final File directory = getDir();
createTree(directory);
tree = new JTree(treeModel);
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setCellRenderer(new FileTreeCellRenderer());
tree.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(e.getClickCount() == 2) {
Object n = selPath.getLastPathComponent();
String sel = n.toString();
File nodeFile = new File(sel);
if(nodeFile.isDirectory() && (!nodeFile.isHidden())) {
UserWindow.printToLog("doubble-click event on folder: " + nodeFile.getName());
//TODO:stuff happening here
}
if(nodeFile.isFile() && (!nodeFile.isHidden())) {
UserWindow.printToLog("doubble-click event on file: " + nodeFile.getName());
new FileTreeEventHandler(nodeFile);
}
}
}
});
JScrollPane sp = new JScrollPane(tree);
jp.add(sp);
JButton updateButton = new JButton("Update");
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
treeModel.reload();
}
});
jp.add(updateButton, BorderLayout.SOUTH);
setVisible(true);
}
private void createTree(File directory) {
root = new DefaultMutableTreeNode();
treeModel = new DefaultTreeModel(root);
DefaultMutableTreeNode node = new DefaultMutableTreeNode(directory);
root.add(node);
populate(directory, node);
}
private void populate(File directory, DefaultMutableTreeNode node) {
String[] files = directory.list();
for(String file : files) {
File currentFile = new File(directory, file);
addLeaf(node, currentFile);
}
}
private void addLeaf(DefaultMutableTreeNode node, File currentFile) {
if(currentFile.isFile() && !currentFile.isHidden()) {
DefaultMutableTreeNode leafFile = new DefaultMutableTreeNode(currentFile);
node.add(leafFile);
}
if(currentFile.isDirectory() && !currentFile.isHidden()) {
DefaultMutableTreeNode folder = new DefaultMutableTreeNode(currentFile);
node.add(folder);
populate(currentFile, folder);
}
}
private File getDir() {
String path = new File(System.getProperty("user.dir"), "downloaded content").getAbsolutePath();
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
return dir;
}
}

treeModel.reload();
Instead of just invoking the above code, I would guess you need to invoke:
createTree(directory);
tree.setModel(treeModel);
to recreate the TreeModel to reflect the new directory structure.

DefaultTreeModel#reload basically states...
Invoke this method if you've modified the TreeNodes upon which this
model depends. The model will notify all of its listeners that the
model has changed below the given node.
This assumes that the model itself has changed.
You have at least two basic course of actions...
You could...
Create a new DefaultTreeModel or
Remove all the nodes from the existing DefaultTreeModel...
And then re-build the model.
If you create a new TreeModel, make sure you set it against the JTree.
This is a little heavy handed, but even if you choose to write the population algorithm so that it checked the existing content of the model, you're still going to have to walk the file structure.
Updating the model could allow you to preserve some of the state of the JTree (ie what nodes are expanded or not, for example)
If you're lucky enough to be using Java 7, you could also take advantage of the File Watcher API, which would allow you to, for example, set each directory node up as a watcher service to monitor it's own content and update itself (add/remove nodes) when changes occur.
Take a look at Watching a Directory for Changes

Related

Java Quiz System, help required in changing the name of a node

Here's the problem:
I have three Classes. One is a DynamicTree, one is called "main application" which all other classes MUST pass through. The other is called "addQForm" which is basically a form to add a node to the Dynamic Tree.
So in my Dynamic Tree there is a group of functions which add a node to the tree. These are as follows.
public DefaultMutableTreeNode addObject(Object child) {
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
}
else {
parentNode = (DefaultMutableTreeNode) (parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child) {
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
if (parent == null) {
parent = rootNode;
}
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
if (shouldBeVisible) {
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
Okay so from here, I have the mainApplication which creates a GUI and adds the Dynamic Tree to it.
treePanel = new DynamicTree();
populateTree(treePanel);
So the Main Application has a button which has the following code:
if (ADD_COMMAND.equals(command)) {
//Add button clicked
addQForm.main(null);
treePanel.addObject(" New Node" + newNodeSuffix);
The Main Application also has the function "add Node" which shows a message dialogue (just to check what is stored in the local variable qTitle).
It then calls the "add Object Function" from the Dynamic Tree.
public void addNode(String qTitle){
JOptionPane.showMessageDialog(null, qTitle, "Error Message",
JOptionPane.ERROR_MESSAGE);
treePanel.addObject(qTitle);
}
So in my third class I have a Text Field and a Button. When The button is clicked the text is extracted from the text field and the form is closed.
public void actionPerformed(ActionEvent e) {
PrintWriter out;
try {
qTitle = qtitle.getText();
out = new PrintWriter(qtitle.getText() + ".txt");
out.println(qtitle.getText());
out.println(q.getText());
out.println(sUnit);
out.close();
dispose();
MainApplication mainapplication = new MainApplication();
mainapplication.addNode(qTitle);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
As you can see I called the function addNode from the main application by instantiating.
BUT the variable is passed through to Main Application as it should however the second line:
treePanel.addObject(qTitle);
Will not function. I have attempted accessing other methods within my Dynamic Tree Class so this is just one example.
Can someone please explain to me why it refuses to complete this line of code?
I figured the error is when I instantiate but I'm not sure why...

JChooser : Restricting view and add to a particular directory tree

This is a question that has been asked before, but there is a bug in that solution.
My requirements are - when user invokes JFileChooser, he should not be able to navigate up the tree.
The answer has been to write a custom FileSystemView -
How do I restrict JFileChooser to a directory?
Has a solution, as does
http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/
However, both of them have a problem sometimes. For the correct implementation, the FileChooser should come up as -
However, sometimes, it appears as -
and user has to click the up arrow to see the correct directory. Any idea why this is happening please? And a solution ?
The code for the custom FileSystemView is
public class SingleRootFileSystemView extends FileSystemView
{
File root;
File[] roots = new File[1];
public SingleRootFileSystemView(File root)
{
super();
this.root = root;
roots[0] = root;
}
#Override
public File createNewFolder(File containingDir)
{
File folder = new File(containingDir, "New Folder");
folder.mkdir();
return folder;
}
#Override
public File getDefaultDirectory()
{
return root;
}
#Override
public File getHomeDirectory()
{
return root;
}
#Override
public File[] getRoots()
{
return roots;
}
}
The code to invoke this is
FileSystemView fsv = new SingleRootFileSystemView(folder);
JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
fileChooser.setFileSelectionMode(1);
int returnVal = fileChooser.showOpenDialog(null);
Thanks very much.

How to disable expand sign in Swing JTree?

I'm working in Swing and I would like to disable the expand (plus [+]) sign on a certain type of nodes.
Not sure how to do it because my nodes aren't leaves and I also cannot use setShowsRootHandles (which is only for the root).
I'm referring to to JTree: suppose i got this structure:
Root
--[+] node1
--[+] node2
when I load this structure i would like not to see the [+] sign on node2 (because it a special type node). But I also would like to expand it by using a special command.
I've overridden isLeaf() (method from DefaultMutableTreeNode) so it would set to to TRUE when i'm in the special type node, but then when I'm trying to expand it, it wouldn't expand because isLeaf() == TRUE...
Hope this will make things more clear.
While it is not possible to remove the handles, it is possible to restrict the expansion of nodes. The way to go is a TreeWillExpandListener combined with a custom treeNode that has state to restrict expansion:
the custom node below has an expandable property that's false by default
when detecting custom nodes, the listener allows/vetoes expansion based on that expandable property
for programmatic expansion, the expandable property is set to true temporarily to pass the listener
Example code:
// mixed tree of normal/restricted noded
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode normalSubTree = new DefaultMutableTreeNode("normal");
normalSubTree.add(new DefaultMutableTreeNode("normalChild"));
MyNode restrictedSubTree = new MyNode("restrictedSubtree");
restrictedSubTree.add(new DefaultMutableTreeNode("restrictedChild"));
root.add(normalSubTree);
root.add(restrictedSubTree);
final JTree tree = new JTree(root);
// the listener which vetos expansion of MyNodes that are not expandable
TreeWillExpandListener l = new TreeWillExpandListener() {
#Override
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
TreePath path = event.getPath();
if (path.getLastPathComponent() instanceof MyNode) {
if (!((MyNode) path.getLastPathComponent()).isExpandable()) {
throw new ExpandVetoException(event, "node not expandable");
}
}
}
#Override
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
}
};
tree.addTreeWillExpandListener(l);
Action expand = new AbstractAction("Expand") {
#Override
public void actionPerformed(ActionEvent e) {
TreePath selected = tree.getSelectionPath();
if (selected == null) return;
if (selected.getLastPathComponent() instanceof MyNode) {
MyNode last = (MyNode) selected.getLastPathComponent();
boolean old = last.isExpandable();
last.setExpandable(true);
tree.expandPath(selected);
last.setExpandable(old);
}
}
};
JXFrame frame = wrapWithScrollingInFrame(tree, "veto expand");
addAction(frame, expand);
show(frame);
}
// custom node which has an expandable property
public static class MyNode extends DefaultMutableTreeNode {
private boolean expandable;
public MyNode() {
this(null);
}
public MyNode(Object userObject) {
super(userObject);
}
public void setExpandable(boolean expandable) {
this.expandable = expandable;
}
public boolean isExpandable() {
return expandable;
}
}
It's possible to remove the handles - despite what others have mentioned.
I've attached a snippet on how to do this below. The key thing is to override shouldPaintExpandControl in BasicTreeUI.
jtree.setUI(new BasicTreeUI() {
#Override
protected boolean shouldPaintExpandControl(final TreePath path, final int row
, final boolean isExpanded, final boolean hasBeenExpanded, final boolean isLeaf)
{
boolean shouldDisplayExpandControl = false;
return shouldDisplayExpandControl;
}
This should really be documented in the JTree API but that's another issue.
Another approach to consider:
If you call DefaultTreeModel(TreeNode root, boolean asksAllowsChildren) the model will "ask" the nodes you insert if they are allowed to have children. If they cannot, it should not display the expand icon.
Be sure to override javax.swing.tree.TreeNode.getAllowsChildren() in your class.

JTree update nodes without collapsing

I have a Java SE 7 application that needs to have the JTree nodes updated. From the tutorial given by Oracle using this thread, there's no given hint on how I could update the label (displayed text of the node on the Tree) on code. Currently I am using DefaultTreeModel as the model of my JTree and DefaultMutableTreeNode as the nodes of the said Tree.
To further detail about the application I am working on, I am developing a chat facility having the contact(s) displayed with their availability status (whether Online, Offline, etc.) per account.
The question is, how can I update the displayed text of a particular node without (at most) removing it from it's parent and adding it on it's designated index. Like a DefaultMutableTreeNode.setText("<new label>")?
UPDATE : January 20, 2013
Redefined the question for clarifications.
Perhaps if you use 'nodeChanged()' instead of 'reload()' you will get the effect you desire.
There are a bunch of methods on the DefaultTreeModel class that cause various parts of the tree to be changed and redrawn. There are also other methods on DefaultTreeModel that only cause redrawing to take place.
You mentioned 'reload(node)' and commented that it causes the tree to collapse when you call it. 'reload' causes the entire sub-tree to be completely redrawn starting at that node. (But if that node isn't visible, it changes nothing.) That is called a 'structure change'.
'insertNodeInto()' and 'removeNodeFromParent()' modify the tree structure by adding or removing the node and then redrawing.
I think 'nodeChanged()' is the one you need since it just notifies the model that something changed in the node that will cause it to display differently. Perhaps the displayable text is now different than it was. Perhaps you changed the user object in the node. That's when you call 'nodeChanged()' on a node.
You should try 'nodeChanged()' in place of the 'reload()' call in your own code that was collapsing and in the example program vels4j provided. This might take care of the problem.
Note that there are also two other families of methods on the DefaultTreeModel that are used in other cases:
These methods work with the tree nodes and use the tree path to define where the change took place. They do not change the data structures underlying the tree but notify the model that something changed so it can notify the listeners that actually redraw things or otherwise respond to changes.
nodesWereInserted()
nodesWereRemovde()
nodesChanged()
nodeStructureChanged()
There are also a set of fire...() methods that are used internally to the DefaultTreeModel and any sub-classes you may create. They merely notify any listeners that something changed. Notice that they are protected.
May this simple and executable program help you to resolve your issue.
public class JTreeDemo extends JPanel
implements Runnable {
private JTree tree;
private DefaultTreeModel treeModel ;
private Random rnd = new Random();
private List<User> userList;
public JTreeDemo() {
super( );
//Create the nodes.
DefaultMutableTreeNode top =
new DefaultMutableTreeNode("Users");
treeModel = new DefaultTreeModel(top);
createNodes(top);
//Create a tree that allows one selection at a time.
tree = new JTree(treeModel);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
//Create the scroll pane and add the tree to it.
JScrollPane treeView = new JScrollPane(tree);
//Add the split pane to this panel.
add(treeView);
}
public String getRandomStatus() {
int nextInt = rnd.nextInt(100);
if( nextInt%2==0) {
return "Online";
} else {
return "Offline";
}
}
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
int nextInt = rnd.nextInt(10);
User user = userList.get(nextInt);
user.setStatus(getRandomStatus());
treeModel.nodeChanged(user);
} catch (InterruptedException ex) {
// handle it if necessary
}
}
}
private class User extends DefaultMutableTreeNode {
public String userName;
public String status;
public User(String name) {
userName = name;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
#Override
public String toString() {
String color = status.equals("Online") ? "Green" : "Red";
return "<html><b color='"+color+"'>"+
userName +"-"+status +"</b></html>";
}
}
private void createNodes(DefaultMutableTreeNode top) {
userList = new ArrayList() ;
for(int i=0;i<10;i++) {
User u1 = new User("User " + (i+1));
u1.setStatus("Online");
top.add(u1);
userList.add(u1);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TreeDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
JTreeDemo jTreeDemo = new JTreeDemo();
frame.add(jTreeDemo);
frame.pack();
frame.setVisible(true);
// update status randomly
Thread thread = new Thread(jTreeDemo);
thread.start();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I've added a Thread to update Status randomly, hope you can modify base on your need.
Output :
Edit:
1. Based on suggestion I've removed reload(node) and added tree model reload.
It's easy if nodes contains objects which are unique in the tree and have implemented method equals and hashCode (for example you show strings or object with unique ID from database). First of all you iterate over all expanded nodes and save objects from the nodes in a set. Then you perform update of the model. After update you iterate over all nodes and if they are in the set you expand the node in the tree.
If nodes are not unique - you need to save in the set the complete tree path (for example as list) and check it after update to expand the nodes.
If objects has neither equals nor hashCode (both these methods must be implemented) - this variant cannot be used.
Just for the record (I voted for Lee Meador), DefaultTreeModel#nodeChanged(javax.swing.tree.TreeNode) is the way to go:
public class TestFrame extends JFrame {
public TestFrame() {
//create gui with simple jtree (and DefaultTreeModel)
JButton changeBtn = new JButton();
final JTree jTree = new JTree();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
changeBtn.setText("update selected node");
getContentPane().add(changeBtn, java.awt.BorderLayout.PAGE_END);
DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode treeNode2 = new DefaultMutableTreeNode("blue");
treeNode1.add(treeNode2);
treeNode2 = new DefaultMutableTreeNode("violet");
DefaultMutableTreeNode treeNode3 = new DefaultMutableTreeNode("red");
treeNode2.add(treeNode3);
treeNode3 = new DefaultMutableTreeNode("yellow");
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);
jTree.setModel(new DefaultTreeModel(treeNode1));
getContentPane().add(jTree, BorderLayout.CENTER);
pack();
//add listener to button, to change selected node on button click
changeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
DefaultMutableTreeNode dmt = (DefaultMutableTreeNode)jTree.getSelectionPath().getLastPathComponent();
//update content/representation of selected node
dmt.setUserObject("My update: " + new Date());
//nodeChanged
((DefaultTreeModel) jTree.getModel()).nodeChanged(dmt);
}
});
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
}

JTree with DefaultTreeModel, how to refresh visually after loading?

I have been searching here and found answers to this problem but can't seem to make them work for me. Basicly I have a GUI that contains a JTree inside a JScrollPane:
private void initComponents() {
scroll = new javax.swing.JScrollPane();
nodo padre = new nodo();
modeloArbol modelo = new modeloArbol(padre);
arbol = new arbolNodos(modelo);
I have the following classes:
public class arbolNodos extends JTree implements Serializable{
public arbolNodos(TreeModel newModel) {
public class listenerModeloArbol implements TreeModelListener{
//Overriding treeNodes*(TreeModelEvent e)
public class modeloArbol extends DefaultTreeModel implements Serializable{
public modeloArbol(TreeNode root) {
super(root);
}
public class nodo extends DefaultMutableTreeNode implements Serializable{
I also have 2 buttons that store (botonGuardarArbol) and retrieve (botonCargarArbol) using the XMLEncoder the JTree (they really retrieve the root node of the tree) into a file with the corresponding actionPerformed listeners:
private void botonGuardarArbolActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("C:\\borrar\\presupuesto")));
encoder.writeObject(arbol.getModel().getRoot());
encoder.close();
private void botonCargarArbolActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
XMLDecoder decoder = new XMLDecoder( new BufferedInputStream(new FileInputStream("C:\\borrar\\presupuesto")));
nodo padre = (nodo) decoder.readObject();
modeloArbol modelo = new modeloArbol(padre);
decoder.close();
modelo.setRoot(padre);
arbolNodos arbolNuevo = null;
if( modelo != null ){
arbolNuevo = new arbolNodos(modelo);
arbol = null;
arbol = arbolNuevo;
((DefaultTreeModel)arbol.getModel()).reload();
}
else
arbolNuevo = new arbolNodos();
The thing is, when I retrieve the stored JTree, I know it is well retrieved because I try printing attributes inside all the nodes of the Tree and they are ok, but when I try putting it up in the Swing it doesn't refresh and the view bloks (ie. I can't manipulate anything in the JTree I had before doing loading). I have tried the numerous threads of refresh/update JTree but couldn't fix it. How can I do this?
Thank you
if( modelo != null )
{
arbolNuevo = new arbolNodos(modelo); //
arbol = null;
arbol = arbolNuevo;
((DefaultTreeModel)arbol.getModel()).reload();
}
else
arbolNuevo = new arbolNodos();
Don't keep creating new JTree objects. If you want to change the model then just use:
tree.setModel(...);
Also, why are you extend JTree, DefaultTreeModel, DefaultMutableTreeNode? If for some reason you do need to extend those classes then follow standard Java naming conventions for those classes. Classes start with an upper case character.

Categories