Originariamente inviato da Rubox
Mi autorispondo.
Rifacendo da zero il JTree con il reload del modello, il TreePath precedente salvato in una variabile non esiste più, poichè con il reload crea dei nuovi oggetti.
Di quali "nuovi" oggetti stai parlando??? Il TreePath resta comunque ancora valido!!!
E questo infatti funziona:
codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TestFrame extends JFrame {
private JTree tree;
private DefaultTreeModel model;
public TestFrame() {
super("Test JTree Add");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 300);
tree = new JTree();
model = (DefaultTreeModel) tree.getModel();
JButton addButton = new JButton("ADD");
getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
getContentPane().add(addButton, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TreePath selPath = tree.getSelectionPath();
if (selPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("hello");
node.add(newNode);
model.reload(node);
tree.expandPath(selPath);
tree.setSelectionPath(selPath);
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
}
E nota che non chiude il resto!!!