Update JTree

0

To see if you can help me, I'm doing a small explorer to list a specific directory, I need to know how to get a button or without a button to update, that is, if I add more files in that directory. Do not have to close and reopen the application, I leave the code.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package paquete;

import javax.swing.JOptionPane;
import java.io.File;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;



/**
 *
 * @author Usuario
 */
public class Principal extends javax.swing.JFrame {
private DefaultMutableTreeNode root;
    public Principal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        ArchivoBtn = new javax.swing.JButton();
        AyudaBtn = new javax.swing.JButton();
        ContactoBtn = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        Explorador = new javax.swing.JTree();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Explorador");

        jToolBar1.setRollover(true);

        ArchivoBtn.setText("Archivo");
        ArchivoBtn.setFocusable(false);
        ArchivoBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ArchivoBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(ArchivoBtn);

        AyudaBtn.setText("Ayuda");
        AyudaBtn.setFocusable(false);
        AyudaBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        AyudaBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        AyudaBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AyudaBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(AyudaBtn);

        ContactoBtn.setText("Contacto");
        ContactoBtn.setFocusable(false);
        ContactoBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ContactoBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        ContactoBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ContactoBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(ContactoBtn);

        File fileRoot = new File("C:\Users\Usuario\Desktop\Test");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        getList(root, new File("C:\Users\Usuario\Desktop\Test"));
        Explorador = new JTree(root);
        Explorador.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        Explorador.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                ExploradorValueChanged(evt);
            }
        });
        Explorador.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                ExploradorPropertyChange(evt);
            }
        });
        jScrollPane2.setViewportView(Explorador);

        jButton1.setText("Refrescar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Label Items");
        jLabel1.setName("lbl"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1))
                .addContainerGap(284, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void AyudaBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void ContactoBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            
        JOptionPane.showMessageDialog(rootPane, "No necesita ayuda","Ayuda",JOptionPane.INFORMATION_MESSAGE);
    }                                           

    private void ExploradorValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                        
        DefaultMutableTreeNode selectedNode =(DefaultMutableTreeNode)Explorador.getSelectionPath().getLastPathComponent();
        jLabel1.setText(selectedNode.getUserObject().toString());


    }                                       

    private void ExploradorPropertyChange(java.beans.PropertyChangeEvent evt) {                                          

    }                                         

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        File fileRoot = new File("C:\Users\Usuario\Desktop\Test");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        getList(root, new File("C:\Users\Usuario\Desktop\Test"));
        Explorador = new JTree(root);
        JOptionPane.showMessageDialog(rootPane, "Actualizando");
        rootPane.repaint();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {

            new Principal().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton ArchivoBtn;
    private javax.swing.JButton AyudaBtn;
    private javax.swing.JButton ContactoBtn;
    private javax.swing.JTree Explorador;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration                   

    public static class FileNode {

       private File file;

        public FileNode(File file) {
            this.file = file;
        }

        @Override
        public String toString() {
            String name = file.getName();
            if (name.equals("")) {
                return file.getAbsolutePath();
            } else {
                return name;
            }
        }
}
    public void getList(DefaultMutableTreeNode node, File f) {
     if(!f.isDirectory()) {
         // We keep only JAVA source file for display in this HowTo

            System.out.println("Archivo  -  " + f.getName());
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(f.getName());
            node.add(child);

         }
     else {
         System.out.println("Directorio  -  " + f.getName());
         DefaultMutableTreeNode child = new DefaultMutableTreeNode(f.getName());
         node.add(child);
         File fList[] = f.listFiles();
         for(int i = 0; i  < fList.length; i++)
             getList(child, fList[i]);
         }
    }
}
    
asked by Tone RV 05.11.2018 в 12:21
source

1 answer

0

With a data model like DefaultTreeModel you can do that refresh . Considering the following:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  File fileRoot = new File("C:\Users\Usuario\Desktop\Test");
  root = new DefaultMutableTreeNode(new FileNode(fileRoot));
  getList(root, new File("C:\Users\Usuario\Desktop\Test"));
  DefaultTreeModel M = new DefaultTreeModel(root);
  M.reload(root);// Actualización del modelo con los datos
  Explorador.setModel(M);// JTree con nuevo modelo de datos...
  //Explorador = new JTree(root);
  JOptionPane.showMessageDialog(rootPane, "Actualizado");
  //rootPane.repaint();
}

Additionally, in the ExploradorValueChanged method, a nullPointerException can be avoided by making a barely substantial modification:

private void ExploradorValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                        
  //DefaultMutableTreeNode selectedNode =(DefaultMutableTreeNode)Explorador.getSelectionPath().getLastPathComponent();
  DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) Explorador.getLastSelectedPathComponent();
  if(selectedNode != null)
    jLabel1.setText(selectedNode.getUserObject().toString());
}
    
answered by 05.11.2018 / 22:37
source