Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] JFileChooser, Listar los ficheros selecionado

Estas en el tema de JFileChooser, Listar los ficheros selecionado en el foro de Java en Foros del Web. Hola, estoy usando la clase JFileChooser, el objetivo de mi caso es ir seleccionando mis ficheros csv, pero que sea de uno a uno, eh ...
  #1 (permalink)  
Antiguo 07/12/2014, 23:41
 
Fecha de Ingreso: noviembre-2014
Mensajes: 26
Antigüedad: 9 años, 5 meses
Puntos: 0
JFileChooser, Listar los ficheros selecionado

Hola, estoy usando la clase JFileChooser, el objetivo de mi caso es ir seleccionando mis ficheros csv, pero que sea de uno a uno, eh ir afichando el nombre del ficheros en mi JFrame. Pense usar un arreglo de jlabel, y hacer un bucle for. Al Final mi resultado debe ser una lista de 4 ficheros(que affiche solo el nombre del fichero).

Ejemplo:

fiche.csv1
fiche.csv2
fiche.csv3
fiche.csv4

Aqui le dejo mi codigo, el me funciona, solo que me aficha un solo fichero:

fiche.csv(el ultimo que carque)

Les agradeceria un consejo:
----------------------------------------------------------------

JFileChooser jf= new JFileChooser();

JFC.setFileFilter(new FileNameExtensionFilter("todos los archivos *.CSV", "csv","CSV"));

int abrir = jf.showDialog(null, "Abrir");
if (abrir == JFileChooser.APPROVE_OPTION) {

File archivo = jf.getSelectedFile();
jLabel1.setText(archivo.getName());
  #2 (permalink)  
Antiguo 09/12/2014, 01:27
 
Fecha de Ingreso: febrero-2005
Mensajes: 39
Antigüedad: 19 años, 2 meses
Puntos: 1
Respuesta: JFileChooser, Listar los ficheros selecionado

Seria algo así (aunque usar un label no creo que sea lo mejor):

jLabel1.setText(jLabel1.getText()+"\n"+archivo.get Name());

Lo que pasa que para utilizar más de una linea en un label tendrías que usar html y seria algo así:

jLabel1.setTex(jLabel1.getText()+"<html>"+archivo. getName()+"<P>");

Saludos,
  #3 (permalink)  
Antiguo 09/12/2014, 15:30
 
Fecha de Ingreso: noviembre-2014
Mensajes: 26
Antigüedad: 9 años, 5 meses
Puntos: 0
Respuesta: JFileChooser, Listar los ficheros selecionado

Gracias Juanjo, no sabia que jlabel soportaba html.....
Pero ,de todos modos esto no me funciono, me sigue remplazando mi jlabel.setText(archivo.getName()) por el proximo fichero que cargo;
  #4 (permalink)  
Antiguo 10/12/2014, 05:13
 
Fecha de Ingreso: febrero-2005
Mensajes: 39
Antigüedad: 19 años, 2 meses
Puntos: 1
Respuesta: JFileChooser, Listar los ficheros selecionado

Buenas Michel, fijate:

jLabel1.setText(jLabel1.getText()+"<html>"+archivo . getName()+"<P>");

a la label le guardas (jLabel1.setText(XXX)) lo que ya contenia (jLabel1.getText()) mas el nuevo archivo seleccionado (archivo. getName()).

Tu solo le guardas el archivo seleccionado (label.setText(archivo.getName()))

el set no es un add lo que guardes reemplaza a lo que habia por tanto debes guardar lo que ya contenía sumado a lo nuevo, con el código HTML te debería poner uno debajo de otro.

Saludos,
  #5 (permalink)  
Antiguo 10/12/2014, 05:28
 
Fecha de Ingreso: febrero-2005
Mensajes: 39
Antigüedad: 19 años, 2 meses
Puntos: 1
Respuesta: JFileChooser, Listar los ficheros selecionado

Hice una pequeña prueba con un boton que llama al selector y una etiqueta y funciona todo OK.

Código Java:
Ver original
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package javaapplication14;
  7.  
  8. import java.io.File;
  9. import javafx.stage.FileChooser;
  10. import javax.swing.JFileChooser;
  11. import javax.swing.filechooser.FileNameExtensionFilter;
  12.  
  13. /**
  14.  *
  15.  * @author juanjo
  16.  */
  17. public class NewJFrame extends javax.swing.JFrame {
  18.  
  19.     /**
  20.      * Creates new form NewJFrame
  21.      */
  22.     public NewJFrame() {
  23.         initComponents();
  24.         jLabel1.setText("");
  25.     }
  26.  
  27.     /**
  28.      * This method is called from within the constructor to initialize the form.
  29.      * WARNING: Do NOT modify this code. The content of this method is always
  30.      * regenerated by the Form Editor.
  31.      */
  32.     @SuppressWarnings("unchecked")
  33.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  34.     private void initComponents() {
  35.  
  36.         jLabel1 = new javax.swing.JLabel();
  37.         jButton1 = new javax.swing.JButton();
  38.  
  39.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  40.  
  41.         jLabel1.setText("jLabel1<P>Prueba");
  42.  
  43.         jButton1.setText("jButton1");
  44.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  45.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  46.                 jButton1ActionPerformed(evt);
  47.             }
  48.         });
  49.  
  50.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  51.         getContentPane().setLayout(layout);
  52.         layout.setHorizontalGroup(
  53.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  54.             .addGroup(layout.createSequentialGroup()
  55.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  56.                     .addGroup(layout.createSequentialGroup()
  57.                         .addGap(22, 22, 22)
  58.                         .addComponent(jLabel1))
  59.                     .addGroup(layout.createSequentialGroup()
  60.                         .addContainerGap()
  61.                         .addComponent(jButton1)))
  62.                 .addContainerGap(288, Short.MAX_VALUE))
  63.         );
  64.         layout.setVerticalGroup(
  65.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  66.             .addGroup(layout.createSequentialGroup()
  67.                 .addGap(21, 21, 21)
  68.                 .addComponent(jLabel1)
  69.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  70.                 .addComponent(jButton1)
  71.                 .addContainerGap(231, Short.MAX_VALUE))
  72.         );
  73.  
  74.         pack();
  75.     }// </editor-fold>                        
  76.  
  77.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  78.         // TODO add your handling code here:
  79.         JFileChooser jf= new JFileChooser();
  80.  
  81.         jf.setFileFilter(new FileNameExtensionFilter("todos los archivos *.CSV", "csv","CSV"));
  82.  
  83.         int abrir = jf.showDialog(null, "Abrir");
  84.         if (abrir == JFileChooser.APPROVE_OPTION) {
  85.  
  86.         File archivo = jf.getSelectedFile();
  87. jLabel1.setText(jLabel1.getText()+"<HTML>"+archivo.getName()+"<P>");
  88.     }
  89.     }                                        
  90.  
  91.     /**
  92.      * @param args the command line arguments
  93.      */
  94.     public static void main(String args[]) {
  95.         /* Set the Nimbus look and feel */
  96.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  97.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  98.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  99.          */
  100.         try {
  101.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  102.                 if ("Nimbus".equals(info.getName())) {
  103.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  104.                     break;
  105.                 }
  106.             }
  107.         } catch (ClassNotFoundException ex) {
  108.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  109.         } catch (InstantiationException ex) {
  110.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  111.         } catch (IllegalAccessException ex) {
  112.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  113.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  114.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  115.         }
  116.         //</editor-fold>
  117.  
  118.         /* Create and display the form */
  119.         java.awt.EventQueue.invokeLater(new Runnable() {
  120.             public void run() {
  121.                 new NewJFrame().setVisible(true);
  122.             }
  123.         });
  124.     }
  125.  
  126.     // Variables declaration - do not modify                    
  127.     private javax.swing.JButton jButton1;
  128.     private javax.swing.JLabel jLabel1;
  129.     // End of variables declaration                  
  130. }
  #6 (permalink)  
Antiguo 10/12/2014, 09:53
 
Fecha de Ingreso: noviembre-2014
Mensajes: 26
Antigüedad: 9 años, 5 meses
Puntos: 0
Respuesta: JFileChooser, Listar los ficheros selecionado

Gracias Juanjo...me funciono perfecto...

Etiquetas: clase, ficheros, jfilechooser
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:25.