JTree与DefaultTreeModel一样,加载后如何刷新?

时间:2011-11-24 16:01:21

标签: java swing model jtree

我一直在这里搜索并找到了这个问题的答案,但似乎无法使它们适合我。基本上我有一个包含JScrollPane中的JTree的GUI:

private void initComponents() {

        scroll = new javax.swing.JScrollPane();
        nodo padre = new nodo();
        modeloArbol modelo = new modeloArbol(padre);
        arbol = new arbolNodos(modelo);

我有以下课程:

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{

我还有2个按钮存储(botonGuardarArbol)并使用XMLEncoder检索(botonCargarArbol)JTree(它们真正检索树的根节点)到具有相应actionPerformed监听器的文件中:

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();

问题是,当我检索存储的JTree时,我知道它已被很好地检索,因为我尝试在树的所有节点内打印属性并且它们没问题,但是当我尝试将它放在Swing中它没有&# 39; t refresh和视图bloks(即我无法在加载之前操作JTree中的任何内容)。我已经尝试了刷新/更新JTree的众多线程,但无法修复它。我怎么能这样做?

谢谢

1 个答案:

答案 0 :(得分:4)

if( modelo != null )
{
    arbolNuevo = new arbolNodos(modelo); // 
    arbol = null;
    arbol = arbolNuevo;
    ((DefaultTreeModel)arbol.getModel()).reload();
}         
else
    arbolNuevo = new arbolNodos(); 

不要继续创建新的JTree对象。如果您想更改模型,请使用:

tree.setModel(...);

另外,为什么要扩展JTree,DefaultTreeModel,DefaultMutableTreeNode?如果由于某种原因,您确实需要扩展这些类,那么请遵循这些类的标准Java命名约定。类以大写字符开头。