Stack Overflow en español Asked by Isa on January 6, 2021
estoy intentando hacer una especie de buscador de archivos. Para ello tengo un JComboBox que extrae las extensiones de los archivos listados y al seleccionar una de ellas la introduce en un JTextField para buscarla. El problema es que solo selecciona la primera extensión y al intentar cambiarla al pulsar el botón de búsqueda se restablece la primera.
Me disculpo por los errores de formato ya que es mi primera vez publicando aquí. Gracias
Inserto el código del pograma:
package pruebaswing;
import java.awt.Frame;
import java.awt.TextField;
import java.util.ArrayList;
import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author isabe
*/
public class Interfaz extends javax.swing.JFrame {
/**
* Creates new form Interfaz
*/
public Interfaz() {
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() {
jProgressBar1 = new javax.swing.JProgressBar();
jFileChooser1 = new javax.swing.JFileChooser();
jFileChooser2 = new javax.swing.JFileChooser();
jOptionPane1 = new javax.swing.JOptionPane();
jMenuItem1 = new javax.swing.JMenuItem();
jDialog1 = new javax.swing.JDialog();
btnBusca = new javax.swing.JButton();
btnExtension = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
texto1 = new javax.swing.JTextField();
texto2 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
miTabla = new javax.swing.JTable();
errorRuta = new javax.swing.JLabel();
errorVacio = new javax.swing.JLabel();
examinar = new javax.swing.JButton();
micombo = new javax.swing.JComboBox<>();
jMenuItem1.setText("jMenuItem1");
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnBusca.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/search1.png"))); // NOI18N
btnBusca.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boton1Action(evt);
}
});
btnExtension.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/search1.png"))); // NOI18N
btnExtension.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExtensionActionPerformed(evt);
}
});
jLabel1.setText("Indique Directorio");
jLabel2.setText("Indique extensión");
texto1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
texto1ActionPerformed(evt);
}
});
texto2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
texto2ActionPerformed(evt);
}
});
DefaultTableModel modelo= new DefaultTableModel(
new Object [][] {
},
new String [] {
"Nombre", "Extensión", "Tamaño", "F/D"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
};
miTabla.setModel(modelo);
jScrollPane1.setViewportView(miTabla);
errorRuta.setForeground(new java.awt.Color(204, 0, 0));
errorRuta.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
errorRuta.setText("No existe la ruta");
errorRuta.setVisible(false);
errorVacio.setForeground(new java.awt.Color(204, 0, 0));
errorVacio.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
errorVacio.setText("Debe introducir una ruta");
errorVacio.setVisible(false);
examinar.setText("Examinar...");
examinar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
examinarActionPerformed(evt);
}
});
micombo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] {}));
micombo.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
micomboItemStateChanged(evt);
}
});
micombo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
micomboActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(texto1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(texto2, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExtension, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(examinar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(micombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(23, 23, 23))
.addComponent(errorRuta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(errorVacio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(texto1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnBusca, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(examinar))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(texto2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel2))
.addComponent(btnExtension, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(micombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(errorRuta)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(errorVacio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(35, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void boton1Action(java.awt.event.ActionEvent evt) {
//Se inicializa todo vacío
DefaultTableModel datos = (DefaultTableModel) miTabla.getModel();
datos.setRowCount(0);
errorRuta.setVisible(false);
errorVacio.setVisible(false);
//obtenemos la ruta del text field
String texto = null;
texto = texto1.getText();
if (!texto.isEmpty()) {
File fichero = new File(texto);
if (fichero.exists()) {
//Vector de ficheros de los que obtendremos los datos
File[] todoslosficheros = fichero.listFiles();
ArrayList miArray = new ArrayList();
for (int i = 0; i < todoslosficheros.length; i++) {
String nombre = todoslosficheros[i].getName();
String extension = null;
for (int j = 0; j < nombre.length(); j++) {
if (nombre.charAt(j) == '.') {
extension = nombre.substring(j, nombre.length());
}
}
//creo objetos con los datos necesarios y los meto en el array
FicheroPersonalizado f = new FicheroPersonalizado(nombre, extension, todoslosficheros[i].length(), todoslosficheros[i].isFile());
miArray.add(f);
}
//meto el contenido del array en un jtable
for (int j = 0; j < miArray.size(); j++) {
datos.addRow(new Object[]{null, null, null, null});
FicheroPersonalizado sacar = (FicheroPersonalizado) miArray.get(j);
miTabla.setValueAt(sacar.getNombre(), j, 0);
miTabla.setValueAt(sacar.getExtension(), j, 1);
miTabla.setValueAt(sacar.getTamanio(), j, 2);
miTabla.setValueAt(sacar.getFod(), j, 3);
}
//Al pulsar el botón la lista de extensiones debe actualizarse
micombo.removeAllItems();
DefaultTableModel tabla = (DefaultTableModel) miTabla.getModel();
int filas = tabla.getRowCount();
if (filas != 0){
//recorro la tabla sacando las extensiones
ArrayList miarray= new ArrayList();
for (int i=0;i<filas;i++){
String extension= (String) tabla.getValueAt(i, 1);
//Compruebo si la extensión está ya en el array y si no la meto
if(!miarray.contains(extension)){
miarray.add(extension);
micombo.addItem(extension);
}
}
}
} else {
errorRuta.setVisible(true);
JOptionPane.showMessageDialog(this,"La ruta seleccionada no existe");
}
} else {
errorVacio.setVisible(true);
JOptionPane.showMessageDialog(this,"Debe introducir una ruta");
}
}
private void btnExtensionActionPerformed(java.awt.event.ActionEvent evt) {
btnBusca.doClick();
//Obtengo los datos del jtable
DefaultTableModel datos = (DefaultTableModel) miTabla.getModel();
int filas = datos.getRowCount();
String texto= texto2.getText();
//Bucle para borrar filas
for (int i = filas-1; i > -1; i--) {
String extensiones = (String) datos.getValueAt(i, 1);
if (extensiones == null) {
extensiones = "";
}
if(!extensiones.equalsIgnoreCase(texto)){
datos.removeRow(i);
}
}
}
private void texto2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void texto1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void examinarActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser miChooser=new JFileChooser();
miChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
miChooser.showOpenDialog(this);
File fichero= miChooser.getSelectedFile();
String ruta= (String) fichero.getAbsolutePath();
texto1.setText(ruta);
System.out.println(ruta);
}
private void micomboItemStateChanged(java.awt.event.ItemEvent evt) {
}
private void micomboActionPerformed(java.awt.event.ActionEvent evt) {
String extension= micombo.getItemAt(micombo.getSelectedIndex());
texto2.setText(extension);
System.out.println(extension);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Interfaz().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnBusca;
private javax.swing.JButton btnExtension;
private javax.swing.JLabel errorRuta;
private javax.swing.JLabel errorVacio;
private javax.swing.JButton examinar;
private javax.swing.JDialog jDialog1;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JFileChooser jFileChooser2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JOptionPane jOptionPane1;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable miTabla;
private javax.swing.JComboBox<String> micombo;
private javax.swing.JTextField texto1;
private javax.swing.JTextField texto2;
// End of variables declaration
}
Esto es lo que hay en la clase FicheroPersonalizado:
package pruebaswing;
/**
*
* @author isabe
*/
public class FicheroPersonalizado {
public String nombre;
public String extension;;
public long tamanio;
public boolean isfile;
public char fod;
public FicheroPersonalizado(String nombre,String extension, long tamanio, boolean isfile) {
this.nombre = nombre;
this.tamanio = tamanio;
this.isfile = isfile;
this.extension= extension;
if (isfile==true){
fod='f';
}
else{
fod='d';
}
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getExtension() {
return extension;
}
public void setExtension(String extensión) {
this.extension = extensión;
}
public long getTamanio() {
return tamanio;
}
public void setTamanio(long tamanio) {
this.tamanio = tamanio;
}
public char getFod() {
return fod;
}
public void setFod(char fod) {
this.fod = fod;
}
}
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP