0

a ver si me podéis ayudar.

Necesito cambiar el color del texto de un nodo en concreto cuando se pulse un botón ya que, ese objeto se pasa añade a un JList y para saber que ya está listado. Así no me genera problemas. Y que cuando esté añadido salga un JOpen Pane diciendo que ya esta.

Este es el código que llevo hasta ahora.

/*
 * 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 java.io.FilenameFilter;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JTree;
import javax.swing.ListModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import paquete.FindCertainExtension.GenericExtFilter;
import classes.FileNode;
import classes.SelectionableTreeNode;
import java.awt.Color;
import java.awt.Component;
import javax.swing.tree.DefaultTreeCellRenderer;



/**
 *
 * @author Usuario
 */
public class Principal extends javax.swing.JFrame {
private SelectionableTreeNode root;
DefaultListModel dlmA = new DefaultListModel(); 
    public Principal() {


    File fileRoot = new File("C:\\Users\\Usuario\\Desktop\\Test");
    root = new SelectionableTreeNode(new FileNode(fileRoot));
    getList( root, fileRoot);
    Explorador = new JTree(root);
    Explorador.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

    initComponents();
     Actualizar();
       }

/**
 * 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() {

    jPanel4 = new javax.swing.JPanel();
    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();
    jPanel1 = new javax.swing.JPanel();
    btnupdt = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    btnadd = new javax.swing.JButton();
    btndel = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    Explorador = new javax.swing.JTree();
    jPanel5 = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList<>();

    javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
    jPanel4.setLayout(jPanel4Layout);
    jPanel4Layout.setHorizontalGroup(
        jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 100, Short.MAX_VALUE)
    );
    jPanel4Layout.setVerticalGroup(
        jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 100, Short.MAX_VALUE)
    );

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

    btnupdt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/refresh.png"))); // NOI18N
    btnupdt.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnupdtActionPerformed(evt);
        }
    });

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

    btnadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/right.png"))); // NOI18N
    btnadd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnaddActionPerformed(evt);
        }
    });

    btndel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/left.png"))); // NOI18N
    btndel.setToolTipText("");
    btndel.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btndelActionPerformed(evt);
        }
    });

    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, false)
                .addComponent(jLabel1)
                .addComponent(btnupdt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnadd, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addComponent(btndel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
            .addContainerGap(27, 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(btnupdt)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnadd, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(btndel)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    Explorador.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
    Explorador.setDragEnabled(true);
    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);

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
    );

    jList1.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "Introduzca las imágenes que desea mostrar" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });
    jList1.setDragEnabled(true);
    jScrollPane1.setViewportView(jList1);

    javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
    jPanel5.setLayout(jPanel5Layout);
    jPanel5Layout.setHorizontalGroup(
        jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 387, Short.MAX_VALUE)
        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE))
    );
    jPanel5Layout.setVerticalGroup(
        jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 279, 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()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(266, 266, 266))
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addGap(31, 31, 31)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, 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, 899, 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.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(217, 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, "El servicio no se encuentra disponible en este momento.","Contacto",JOptionPane.INFORMATION_MESSAGE);
}                                           

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

}                                         

private void ExploradorValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                        
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) Explorador.getLastSelectedPathComponent();

    if(selectedNode != null){
        jLabel1.setText(selectedNode.getUserObject().toString());
    }



}                                       

private void btndelActionPerformed(java.awt.event.ActionEvent evt) {                                       
    try{
        int index = jList1.getSelectedIndex();
        dlmA.remove(index);
    }catch(Exception e){
                JOptionPane.showMessageDialog(rootPane, "Debe clickar en una imagen para retirar","Error",JOptionPane.INFORMATION_MESSAGE);

    }



}                                      

private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {                                       
   dlmA.addElement(Explorador.getLastSelectedPathComponent());
   jList1.setModel(dlmA);

String jTreeVarSelectedPath = "";
Object[] paths =  Explorador.getSelectionPath().getPath();
for (int i=0; i<paths.length; i++) {
    jTreeVarSelectedPath += paths[i];
    if (i+1 <paths.length ) {
        jTreeVarSelectedPath += File.separator;
    }

}
   System.out.println("C:\\Users\\Usuario\\Desktop\\"+jTreeVarSelectedPath);

  DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) Explorador.getCellRenderer();
  renderer.setTextSelectionColor(Color.GREEN);
  Explorador.repaint(); 






}                                      

private void btnupdtActionPerformed(java.awt.event.ActionEvent evt) {                                        

  final TreeExpansionUtil expander = new TreeExpansionUtil(Explorador);
  final String state = expander.getExpansionState();
  Actualizar();
  expander.setExpansionState(state);
}                                       

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



    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 btnadd;
private javax.swing.JButton btndel;
private javax.swing.JButton btnupdt;
private javax.swing.JLabel jLabel1;
private javax.swing.JList<String> jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JToolBar jToolBar1;
// End of variables declaration                   


public void getList(SelectionableTreeNode node, File f) {

 if(!f.isDirectory()) {

     // We keep only JAVA source file for display in this HowTo


        SelectionableTreeNode child = new SelectionableTreeNode(f.getName());
        node.add(child);



     }

 else {
     SelectionableTreeNode child = new SelectionableTreeNode(f.getName());
     node.add(child);
     File fList[] = f.listFiles();
     for(int i = 0; i  < fList.length; i++)
         getList(child, fList[i]);


     }




}   

//Método para Actualizar el JTree
public void Actualizar(){

    File fileRoot = new File("C:\\Users\\Usuario\\Desktop\\Test");
    root = new SelectionableTreeNode(new FileNode(fileRoot));
    getList(root, fileRoot);
    DefaultTreeModel M = new DefaultTreeModel(root);
    M.reload(root);// Actualización del modelo con los datos
    Explorador.setModel(M);// JTree con nuevo modelo de datos
}   

public class GenericExtFilter implements FilenameFilter {

    private String ext;

    public GenericExtFilter(String ext) {
        this.ext = ext;
    }

    public boolean accept(File dir, String name) {
        return (name.endsWith(ext));
    }
}

static class CustomDefaultTreeCellRenderer extends DefaultTreeCellRenderer {
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        boolean enabled = false; // <-- here is your logic for enable/disable cell

        sel = enabled;
        hasFocus = enabled;

        Component treeCellRendererComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
        treeCellRendererComponent.setEnabled(enabled);

        return treeCellRendererComponent;
    }
}

}

1 respuesta 1

0

Con este codigo puedes cambiar el icono de los elementos del Jtree. Solo tendrias que hacer una comparacion de lo que te interesa para que solo este sea modificado.\

ImageIcon leafIcon = new ImageIcon(getClass().getResource("/pruebasmultiples/emoticon2.jpeg"));
    if (leafIcon != null) {
        DefaultTreeCellRenderer renderer = 
            new DefaultTreeCellRenderer();
        renderer.setLeafIcon(leafIcon);
        arbol.setCellRenderer(renderer);
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.