Reputation: 597
I have a JTree that shows files and folders of a directory. Also there is a button that disables some of the nodes in the JTree
(using DefaultTreeCellRenderer
).
The item gets disabled when I press the button, but JTree does not show it as a disabled item. Until I click somewhere, or in on if the items of the tree, then it also shows the disabled look of the item.
I know there is a reload()
method for DefaultTreeModel
. But I use a customised model. So this method doesnt work. Here is the model that I use to list files and folders: FileSystemModel
And this is my code:
public class FileViewer {
JFrame frame;
JPanel panel;
JTree tree;
File root;
public ArrayList<String> disabledNodes = new ArrayList<String>();
public FileViewer(){
frame = new JFrame("File Viewer");
panel = new JPanel(new BorderLayout());
root = new File("D:\\Documents\\A X");
FileSystemModel model = new FileSystemModel(root);
tree = new JTree();
tree.setModel(model);
panel.add(tree, BorderLayout.CENTER);
JButton press = new JButton("Press");
panel.add(press, BorderLayout.SOUTH);
press.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
disabledNodes.add("folder1");
}
});
tree.setCellRenderer(new CustomDefaultTreeCellRenderer());
frame.add(panel);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new FileViewer();
}
class CustomDefaultTreeCellRenderer extends DefaultTreeCellRenderer{
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus){
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
File node = (File)value;
String name = node.getName();
for(String element : disabledNodes){
if(name.equals(element)){
this.setEnabled(false);
}
}
return this;
}
}
}
However, in the ActionListener
of the button, I added tree.updateUI();
and it perfectly worked. But somehow I have heard updating UI is a bad practice since it will make other problems later. So is using updateUI
correct here? or there is a better way to make the UI
updated with clicks and user interactions?
Note, I will not add or remove any file from the tree, I just have to enable/disable nodes.
UPDATE: I just notice there is a repaint()
option that does similar function for me. But still, Is it the right way of refreshing the JTree?
Upvotes: 1
Views: 1559