The code below displays a JFrame with a JScrollPane containing a JTree with just a root node ("root").
At the bottom of the frame is a button that when pressed re-initialises the JTree with no arguments (line 42). Hence once the button is clicked the JTree should have some elements in it (those default ones : colours, sports, food).
However, the reinitialised JTree is not displayed. What's the problem?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
class
Test extends JFrame implements ActionListener {
private JScrollPane treeScrollPane;
private JTree tree;
private DefaultMutableTreeNode root;
private JButton runButton;
public Test() {
super("Test");
this.tree = new JTree(this.root = new DefaultMutableTreeNode("root"));
this.treeScrollPane = new JScrollPane(this.tree);
this.treeScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Tree panel"),
BorderFactory.createEmptyBorder(5,5,5,5)));
this.runButton = new JButton("click me");
this.runButton.addActionListener(this);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(this.treeScrollPane, BorderLayout.CENTER);
contentPane.add(this.runButton, BorderLayout.SOUTH);
this.setSize(300, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == this.runButton) {
System.out.println("DEBUG : button clicked");
this.tree = new JTree();
this.tree.expandPath(new TreePath(this.tree.getModel().getRoot()));
}
}
public static void main(
String args[]) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println(e.getMessage());
}
new Test();
}
}