Return database search data in JTable

0

I'm developing an interface that should return a JTable of the values of a mysql table. I 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's a select in this case). However, it points to the following error:

  

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

and points to the line:

modelo = (DefaultTableModel) table.getModel();
    
asked by anonymous 27.05.2018 / 00:45

1 answer

0

You are trying to retrieve a model from a table that has not yet been created. This is the cause of nullpointer , the variable table is null.

You can not suggest anything because this new code does not make much sense, but if you do not create the table already populated 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 does not have to do with the initial question, as this code is, it will not display the table, and there is no need to instantiate a new table or add it to the scroll container every time a search. Then change the lines:

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

To:

table.setModel(modelo);

Move the addition of the table or to the class constructor or add a validation that prevents the line below from setting the table more than once as viweport of JScrollPane:

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

You will also need to instantiate the table in the respective field:

private JTable table =  new JTable();

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

    
27.05.2018 / 03:27