How to popular a Jtable using a . txt file?

Asked

Viewed 2,475 times

4

I wonder how do I make to popular one JTable using a pre-existing text file.

Imagem

I have a query table and I want the user when placing the account number, it shows the data on Jtable and also how I can do the filtering by the agency number ?

The data from my text file: http://pastebin.com/JwasUFKs

Here as they are represented respectively:

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
}

1 answer

4


First thing, avoid code generator, especially this one from Netbeans, it’s sad to work with the code generated by it.

If you need some swing interfaces, consider using Window Builder in the eclipse, the code generated by it is more decent.

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

To edit the data of a JTable it is necessary to update the data of 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 the TableModel of his JTable is initiated (jTable1.setModel) with a DefaultTableModel, still no data (or rather a null data line).

To facilitate data manipulation, as opposed to creating an anonymous class like the generator did, which makes it very difficult to work with the data, create a class that extends from DefaultTableModel and put this generated code there (you can extend directly from AbstractTableModel and implement his abstract methods, I prefer, the code is cleaner and simpler to be customized). It will look 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 the TelaConsulta instead of having that "primeiro-trecho" from above, 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, that 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 am calling it at the end of initComponents (updateTable(jTable1);). Stayed 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:

Exemplo da JTable

P.S.: all the code has been edited in another text editor, maybe netbeans won’t let you change these sections.

  • And how do I do the filtering by the agency ? I would have to make a class of control just for this functionality ?

  • Dude but how to change the data of the instance of Mytablemodel ? I didn’t understand this part very well

  • And as I call the method for actionPerformed ?

  • @Jarwin 1) I don’t understand when you say do the filtering by the agency. Do you want to display everything in the table, then filter? If yes, you should implement something to filter for this, using the data from TableModel even. 2) To JTable has an instance of MyTableModel associated with it. For the data to be updated MyTableModel should be amended. 3) To call a actionPerformed in his case, jTable1 should be an instance variable, not local.

  • The filtering by the agency would be the user by placing the number of the same, Jtable show the respective data to this agency.

  • @Jarwin Right, then you have to do something to filter and re-export on the same table.

  • Okay, thanks for the force there, man.

  • Face only a doubt! You used the search button or when you start the project the data already appear in direct Jtable?

  • @Jarwin in the example I don’t use the button, but just do as I told you in a previous comment.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.