How popular is a JTable using a .txt file?

4

I would like to know how to make a JTable popular using a pre-existing text file.

IhaveaquerytableandIwanttheusertoputtheaccountnumber,itshowsthedatainJtableandalsohowcanIdothefilteringbytheagencynumber?

Thedatafrommytextfile: link

Here as they are respectively represented:

agencia;conta;data de lançamento; valor; operação.

My class ArquivoTextoProvider which reads and writes data:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class ArquivoTextoProvider {

    //Recebe como parãmetro o path do arquivo e o texto a ser gravado
    public static void gravar(String path,String texto){
        File arq = new File(path);
        try {
            FileWriter fw = new FileWriter(arq,true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(texto+"\n");
            bw.close();
            fw.close();
        } catch (IOException e) {

        }
    }

    //Recebe como parãmetro o path do arquivo a ser lido
    //Retorna um ArrayList com todas as linhas gravadas no arquivo
    public static ArrayList<String> carregarLinhas(String path){
        File arq = new File(path);
        try {
            FileReader fr = new FileReader(arq);
            BufferedReader br = new BufferedReader(fr);
            String linha=null;
            ArrayList<String> lista = new ArrayList<String>();
            while ((linha = br.readLine()) != null) {
                lista.add(linha);
            }
            br.close();
            fr.close();
            return lista;
        }catch (Exception ex){

            return null;
        }
    }

    //Recebe como parametro o simbolo separador e uma linha
    //e retorna um vetor de String preenchido com todos os dados separados pelo separado
    public static String[] lerDados(String separador, String linha){
        return linha.split(separador);
    }
}

Class telaConsulta :

package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TelaConsulta extends javax.swing.JFrame {

/**
 * Creates new form TelaLogin
 */
public TelaConsulta() {
    initComponents();
    btConsultar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
           //pesquisar a situação
        }
    } );

}

/**
 * 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">//GEN-BEGIN:initComponents
private void initComponents() {

    jLabel4 = new javax.swing.JLabel();
    edConta = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    edAgencia = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    edData1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    edData2 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    cbMes = new javax.swing.JComboBox();
    btConsultar = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jLabel6 = new javax.swing.JLabel();
    edSaldo = new javax.swing.JTextField();

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

    jLabel4.setText("Conta:");

    edConta.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            edContaActionPerformed(evt);
        }
    });

    jLabel1.setText("Agencia");

    edAgencia.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            edAgenciaActionPerformed(evt);
        }
    });

    jLabel3.setText("Data 1:");

    jLabel2.setText("Data 2:");

    edData2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            edData2ActionPerformed(evt);
        }
    });

    jLabel5.setText("Mes");

    cbMes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));

    btConsultar.setText("Pesquisar");
    btConsultar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btConsultarActionPerformed(evt);
        }
    });

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null}
        },
        new String [] {
            "Data", "Valor", "Operacao"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class
        };
        boolean[] canEdit = new boolean [] {
            false, false, false
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(jTable1);

    jLabel6.setText("Saldo: R$");

    edSaldo.setEditable(false);
    edSaldo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            edSaldoActionPerformed(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()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel6)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(edSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addGap(54, 54, 54)
                                    .addComponent(jLabel1)
                                    .addGap(75, 75, 75)
                                    .addComponent(jLabel3))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(btConsultar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(edConta))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(edAgencia, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(edData1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(3, 3, 3)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(edData2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(cbMes, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addGap(114, 114, 114)
                                    .addComponent(jLabel5)))))
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel4)
                .addComponent(jLabel1)
                .addComponent(jLabel3)
                .addComponent(jLabel2)
                .addComponent(jLabel5))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(edConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(edAgencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(edData1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(edData2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(cbMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(btConsultar)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel6)
                .addComponent(edSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(14, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>//GEN-END:initComponents

private void edContaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edContaActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_edContaActionPerformed

private void edAgenciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edAgenciaActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_edAgenciaActionPerformed

private void edData2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edData2ActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_edData2ActionPerformed

private void btConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConsultarActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_btConsultarActionPerformed

private void edSaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edSaldoActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_edSaldoActionPerformed

/**
 * @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(TelaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TelaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TelaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TelaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new TelaConsulta().setVisible(true);
        }
    });
}

// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btConsultar;
private javax.swing.JComboBox cbMes;
private javax.swing.JTextField edAgencia;
private javax.swing.JTextField edConta;
private javax.swing.JTextField edData1;
private javax.swing.JTextField edData2;
private javax.swing.JTextField edSaldo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
    
asked by anonymous 03.05.2015 / 03:44

1 answer

4

First thing, avoid code generator, especially this NetBeans, it is sad to work with the code generated by it.

If you need some swing builder, consider using Window Builder in eclipse, the code it generates is more decent .

I will try to help you, in a simple way and starting from the generated code that you presented.

To edit data for a JTable you need to update the TableModel linked to JTable .

See this excerpt generated ( primeiro-trecho ):

jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {{null, null, null}}, new String[] {"Data", "Valor", "Operacao"}) {
    Class[] types = new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class};
    boolean[] canEdit = new boolean[] {false, false, false};

    @Override
    public Class getColumnClass(final int columnIndex) {
        return types[columnIndex];
    }

    @Override
    public boolean isCellEditable(final int rowIndex, final int columnIndex) {
        return canEdit[columnIndex];
    }

});

See that TableModel of your JTable is started ( jTable1.setModel ) with DefaultTableModel , still no data (or rather, a null data line).

To make it easier to manipulate the data, as opposed to creating an anonymous class as the generator did, which makes it very difficult to work with the data, create a class that extends DefaultTableModel and place this generated code there (you can extend directly from AbstractTableModel and implement the abstract methods of it, I prefer, the code gets cleaner and more simple to be customized). It will look something like this:

public class MyTableModel extends DefaultTableModel {

    public MyTableModel(final Object[][] dados) {
        super(dados, new String[] {"Data", "Valor", "Operacao"});
    }

    // usaremos este método para atualizar os dados da JTable
    public void setDados(final Object[][] dados) {
        dataVector = super.convertToVector(dados);
    }

    private final Class[] types = new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class};
    private final boolean[] canEdit = new boolean[] {false, false, false};

    @Override
    public Class getColumnClass(final int columnIndex) {
        return types[columnIndex];
    }

    @Override
    public boolean isCellEditable(final int rowIndex, final int columnIndex) {
        return canEdit[columnIndex];
    }

}

Now, in TelaConsulta instead of having that " primeiro-trecho " up there, we'll have something like this:

final Object[][] dados = null;

final MyTableModel myTableModel = new MyTableModel(dados);

jTable1.setModel(myTableModel);

To update the table you must change the dados of the instance of MyTableModel , which is myTableModel , the one we created earlier.

As an example I created the method below that reads a file with the 5 lines of the file you provided and I'm calling it at the end of initComponents ( updateTable(jTable1); ). It looks like this:

private void updateTable(final JTable jTable1) {
    final MyTableModel tableModel = (MyTableModel) jTable1.getModel();
    final Object[][] dados = new Object[5][3];
    final List<String> lines = ArquivoTextoProvider.carregarLinhas("src/data.txt");
    for (int i = 0; i < lines.size(); i++) {
        final String[] data = ArquivoTextoProvider.lerDados(";", lines.get(i));
        dados[i][0] = data[2];
        dados[i][1] = data[3];
        dados[i][2] = data[4];
    }

    tableModel.setDados(dados);
    // notifica o componente de que houve alteração, para que ele atualize considerando agora os novos dados
    jTable1.updateUI();
}

After this, we have the following result:

Q.: All code has been edited in another text editor, netbeans may not let you change these sections.

    
03.05.2015 / 05:09