Add serialized data to a JTable JTable

0

I have this fragment of code where the if question if it was not written in all the JTextField and if it does it creates the file (the file saves an arraylist) .. now, my doubt comes from how I do to show the data of the file in a JTable that is in another class.

    if (nombre.getText().equals("") != (documento.getText().equals("")) != (apellido.getText()).equals("")) {

        JOptionPane.showMessageDialog(this, "POR FAVOR LLENAR TODAS LAS CASILLAS ", "ERROR", JOptionPane.OK_OPTION);

    } else {
        lista.add(new Datos.Hotel(documento.getText(), nombre.getText(), apellido.getText(), habitacion.getText()));

        try {
            FileOutputStream fos = new FileOutputStream("L:\final\PruebaHotel.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(lista);
            JOptionPane.showMessageDialog(null, "Datos guardados");
            oos.close();// cierra el archivo

        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "El archivo no existe " + e);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Los datos de salida no son correctos " + ex);
        }

    }
    
asked by Deiby Peralta 03.06.2017 в 15:39
source

1 answer

0

First you must read the file, I recommend that you check if you are writing the file by lines or everything followed since this solution is only if the records of the file are separated by line break, that's the solution:

  

Note: this code is extracted from link

try{
        FileInputStream fstream = new FileInputStream("LeerArchivo.java");
        DataInputStream entrada = new DataInputStream(fstream);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
        String strLinea;
        while ((strLinea = buffer.readLine()) != null)   {
            System.out.println (strLinea);
        }
        entrada.close();
    }catch (Exception e){
        System.err.println("Ocurrio un error: " + e.getMessage());
    }

If it's all in one line but you separate it by commas or something, just change it by strLinea = buffer.readLine; and then use the split function to separate it.

Then you pass that line data to a list of objects.

and to show it in a serious jTable:

  

This is from my XP authority

//Aqui estas sacando el modelo de tu jTable        
DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            //Esta es la lista de objetos que generaste a partir de tu archivo
            ArrayList<objeto_individual> lista;
            Object[] fila = new Object[modelo.getColumnCount()];
            for(int i=0;i<lista.size();i++){
                //aqui vas seteando cada columna
                fila[0] = lista.get(i).get();
                fila[1] = lista.get(i).get();
                fila[2] = lista.get(i).get();

                modelo.addRow(fila);
            }
    
answered by 03.06.2017 в 20:02