Return search data to database in Jtable

Asked

Viewed 833 times

0

I’m developing an interface that should return in a JTable values of a mysql table. I have developed the following method:

public class Teste extends javax.swing.JFrame {

    private JTable table;
    DefaultTableModel modelo = new DefaultTableModel();

    public Teste() {
        initComponents();
    }

    public void popularJtable(String sql) {

        try {
            Connection con = new ConnectionFactory().getConnection();
            PreparedStatement stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery(sql);
            modelo = (DefaultTableModel) table.getModel();

            modelo.addColumn("tipoCurso");
            modelo.addColumn("nomeCurso");

            while (rs.next()) {
                modelo.addRow(new Object[]{
                    rs.getString("tipoCurso"),
                    rs.getString("nomeCurso")
                });
            }
            table = new JTable(modelo);
            jScrollPaneCursos = new JScrollPane(table);
            stmt.close();
            con.close();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPaneCursos = new javax.swing.JScrollPane();
        Pesquisar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Pesquisar.setText("Pesquisar");
        Pesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PesquisarActionPerformed(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)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addComponent(jScrollPaneCursos, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(146, 146, 146)
                        .addComponent(Pesquisar)))
                .addContainerGap(77, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(93, Short.MAX_VALUE)
                .addComponent(Pesquisar)
                .addGap(18, 18, 18)
                .addComponent(jScrollPaneCursos, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(66, 66, 66))
        );

        pack();
    }// </editor-fold>                        

    private void PesquisarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String sql = "SELECT tipoCurso, NomeCurso FROM curso";
        popularJtable(sql);
    }                                         

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Teste().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Pesquisar;
    private javax.swing.JScrollPane jScrollPaneCursos;

}

The idea is to call this method inside a search button, where I pass a string with the mysql script (it is a select in this case). However, it points out the following error:

Exception in thread "AWT-Eventqueue-0" java.lang.Nullpointerexception

and points to the line:

modelo = (DefaultTableModel) table.getModel();
  • I redesigned the project, tested and the problem remains the same and in the same line. The table that was to appear was the course table, which has the columns idCurso, typeCurso and nomeCurso.

  • On which line now?

  • model = (Defaulttablemodel) table.getModel();

2 answers

0

The section below is incorrect. First we have to instantiate the table(Jtable) object in order to use its attributes

modelo = (DefaultTableModel) table.getModel();
        modelo.addColumn("tipoCurso");
        modelo.addColumn("nomeCurso");
        while (rs.next()) {
            modelo.addRow(new Object[]{
                rs.getString("tipoCurso"),
                rs.getString("nomeCurso")
            });
        }
        table = new JTable(modelo);

Follow below the correct mode:

table = new JTable(modelo);
modelo = (DefaultTableModel) table.getModel();
        modelo.addColumn("tipoCurso");
        modelo.addColumn("nomeCurso");
        while (rs.next()) {
            modelo.addRow(new Object[]{
                rs.getString("tipoCurso"),
                rs.getString("nomeCurso")
            });
        }

0


You are trying to retrieve a model from a table that hasn’t even been created yet. This is the cause of nullpointer, the variable table is void.

Nor can you suggest anything because this new code doesn’t make much sense, but if you don’t create the already populated table when the application starts, remove this line:

modelo = (DefaultTableModel) table.getModel();

Since the model has already been instantiated as DefaultTableModel along with the class.

Although this correction has nothing to do with the initial question, the way this code is, it will not display the table, and there is no need to instantiate a new table or add it to the scrolled container each time a query is made. Then change the lines:

table = new JTable(modelo);
jScrollPaneCursos = new JScrollPane(table);

for:

table.setModel(modelo);

Move the table addition or to the class constructor or add a validation that prevents the row below setting more than once the table as viweport jscrollpane:

if(jScrollPaneCursos.getViewPort().getView() == null) {
    jScrollPaneCursos.setViewportView(table);
}

It will also be necessary to instantiate the table in the respective field:

private JTable table =  new JTable();

To display new data in the table it is not necessary to recreate it or add it more than once to the container. JTable in itself is only a visual component, who manages the data within it is the model, therefore, just change the model that the data will be displayed and modified.

  • This change solved the nullpointer exception, however, the table does not appear yet.

  • I intend, that after pressing the search button, the table appears loaded with the records.

  • @Costa.Gustavo edited the answer, but I suggest that the next question always be clear and objective in your doubts, providing a minimum example.

  • Thank you Articuno, I will try to be clearer next time. Peace be with you.

Browser other questions tagged

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