I’m having problems with Exception in thread "AWT-Eventqueue-0" and I’m not getting it right

Asked

Viewed 15 times

0

I need to put information from a database into a Jtable and I’m not getting out of that internship and I can’t find it on the Internet. In this project I need to register residents in an Sqlite, being able to edit and delete as well, all this within a jFrame, but I can’t get out of the part of putting comic information in Jtable.

Follow the error:

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
    at Connecti.ConnectionF.PreparedStatement(ConnectionF.java:45)
    at modeldao.MoradorDAO.read(MoradorDAO.java:98)
    at view.PrincipalPainel.readJTable(PrincipalPainel.java:187)
    at view.PrincipalPainel.(PrincipalPainel.java:17)
    at view.PrincipalPainel$3.run(PrincipalPainel.java:178)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Connectionf.java.

package Connecti;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionF {
    private Connection connect;
    // conectar ao banco de dados
    public boolean Conectar(){
        try{
            String url = "jdbc:sqlite:system.db";
            connect = DriverManager.getConnection(url);
        }catch(SQLException e){
            System.err.println(e.getMessage());
            return false;
        }
        System.out.println("Conectou!");
        return true;
    }
    //Desconectar do banco de dados
    public boolean Desconectar(){
        try{
            if(connect.isClosed() == false){
                connect.close();
            }
        }catch(SQLException e){
            System.err.println(e.getMessage());
            return false;
        }
        System.out.println("Desconectou!");
        return true;
    }
    public Statement Statement(){
        try{
            return connect.createStatement();
        }catch(SQLException e){
            return null;
        }
    }
    public PreparedStatement PreparedStatement(String sql){
        try{
            return connect.prepareStatement(sql);
        }catch(SQLException e){
            return null;
        }
    }
}

Moradordao.java

package modeldao;

import Connecti.ConnectionF;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelbean.Morador;
import view.PrincipalPainel;

public class MoradorDAO {
    private int numM;
    private String nomeM;
    private String enderecoM;
    private String telefoneM;
    public void create(){
        ConnectionF con = new ConnectionF();
        String sql = "CREATE TABLE IF NOT EXISTS tbl_morador"
                + "("
                + "numero int(6),"
                + "nome varchar(60) NOT NULL,"
                + "endereco varchar(100) NOT NULL,"
                + "telefone varchar(20)"
                + ");";
        //executando o sql para criar a tabela
        boolean conectou = false;
        conectou = con.Conectar();
        try{
            Statement stmt = con.Statement();
            stmt.execute(sql);
            System.out.println("Tabela Morador Criada!");
        }catch(SQLException e){
            System.err.println(e.getMessage());
        }finally{
            if(conectou){
                con.Desconectar();
            }
        }
    }
    
    public void inserir(){
        ConnectionF con = new ConnectionF();
        Morador morador = new Morador();
        PrincipalPainel Painel = new PrincipalPainel();
        this.numM = Integer.parseInt(Painel.getTnumeroM().getText());
        this.nomeM = Painel.getTnomeM().getText();
        this.enderecoM = Painel.getTendeM().getText();
        this.telefoneM = Painel.getTteleM().getText();
        morador.setNome(this.nomeM);
        morador.setEndereco(this.enderecoM);
        morador.setTelefone(this.telefoneM);
        con.Conectar();
        String sqlInsert = " INSERT INTO tbl_morador("
                + "numero,"
                + "nome,"
                + "endereco,"
                + "telefone,"
                + ") VALUES(?,?,?,?)"
                + ";";
        PreparedStatement preparedStatement = con.PreparedStatement(sqlInsert);
        try{
            preparedStatement.setInt(1, morador.getNumero());
            preparedStatement.setString(2, morador.getNome());
            preparedStatement.setString(3, morador.getEndereco());
            preparedStatement.setString(4, morador.getTelefone());
            int resultado = preparedStatement.executeUpdate();
            if(resultado == 1){
                System.out.println("Morador inserido!");
            }else{
                System.out.println("Morador não inserido.");
            }
        }catch(SQLException e){
            System.err.println(e.getMessage());
            System.out.println("Morador não inserido.");
        }finally{
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(MoradorDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            con.Desconectar();
        }
    }
    public List<Morador> read(){
        ConnectionF con = new ConnectionF();
        PreparedStatement pstmt = null;
        ResultSet resultset = null;
        
        List<Morador> moradores = new ArrayList<>();
        
        try {
            pstmt = con.PreparedStatement("SELECT * FROM tbl_morador");
            resultset = pstmt.executeQuery();
            
            while(resultset.next()){
                Morador morador = new Morador();
                
                morador.setNumero(resultset.getInt("numero"));
                morador.setNome(resultset.getString("nome"));
                morador.setEndereco(resultset.getString("endereco"));
                morador.setTelefone(resultset.getString("telefone"));
                moradores.add(morador);
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(MoradorDAO.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            if(pstmt != null){
                try {
                    pstmt.close();
                } catch (SQLException ex) {
                    Logger.getLogger(MoradorDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return moradores;
    }
}

Main Java Panel.

package view;
import Connecti.ConnectionF;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import modelbean.Morador;
import modeldao.MoradorDAO;
/**
 *
 * @author otavio
 */
public class PrincipalPainel extends javax.swing.JFrame {
    public PrincipalPainel() {
        initComponents();
        DefaultTableModel modelo = (DefaultTableModel) jTableM.getModel();
        jTableM.setRowSorter(new TableRowSorter(modelo));
        readJTable();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableM = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        TnomeM = new javax.swing.JTextField();
        TendeM = new javax.swing.JTextField();
        TteleM = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        TnumeroM = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTableM.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nº", "Nome", "Endereço", "Telefone"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

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

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Nome:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("Endereço:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setText("Telefone:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel4.setText("Portaria Portal do Lago");

        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Buscar");

        jButton3.setText("Excluir");

        jButton4.setText("Atualizar");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Nº:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 944, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(TnomeM))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(TteleM))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(TendeM, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(93, 93, 93)
                                        .addComponent(jLabel4))
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(TnumeroM, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(jButton1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton4)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel4)
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TnomeM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(TendeM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(TnumeroM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(TteleM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        ConnectionF con = new ConnectionF();
        MoradorDAO morador = new MoradorDAO();
        morador.inserir();
        
    }                                        
    public static void main(String args[]) {
        ConnectionF con = new ConnectionF();
        MoradorDAO morador = new MoradorDAO();
        morador.create();
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PrincipalPainel().setVisible(true);
            }
        });
    }
    public void readJTable(){
        DefaultTableModel modelo = (DefaultTableModel) jTableM.getModel();
        
        MoradorDAO mdao = new MoradorDAO();
        
        for(Morador m: mdao.read()){
            modelo.addRow(new Object[]{
                m.getNumero(),
                m.getNome(),
                m.getEndereco(),
                m.getTelefone()
            });
        }
    }

    public JTextField getTnumeroM() {
        return TnumeroM;
    }
    public void setTnumeroM(JTextField TnumeroM) {
        this.TnumeroM = TnumeroM;
    }
    public JTextField getTendeM() {
        return TendeM;
    }
    public void setTendeM(JTextField TendeM) {
        this.TendeM = TendeM;
    }
    public JTextField getTnomeM() {
        return TnomeM;
    }
    public void setTnomeM(JTextField TnomeM) {
        this.TnomeM = TnomeM;
    }
    public JTextField getTteleM() {
        return TteleM;
    }
    public void setTteleM(JTextField TteleM) {
        this.TteleM = TteleM;
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextField TendeM;
    private javax.swing.JTextField TnomeM;
    private javax.swing.JTextField TnumeroM;
    private javax.swing.JTextField TteleM;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    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.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableM;
    // End of variables declaration                   
}

Project link with error: https://github.com/Randow137/Tabela-Condominio

No answers

Browser other questions tagged

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