Pessoal… estou com um erro que está me enchendo o saco e não consigo achar a solução.
É o seguinte… tenho 4 class
1 - Class CadastroClienteGraf que é a parte visual do programa, que possui os campos a serem preenchidos (JTextField).
2 - Class ClientesDAO que possui os metodos gravar no banco de dados.
3 - Class ClienteJavaBean que tem as variaveis com os metodos get e set.
4 - Class conexao que faz a conexao com o banco de dados.
Quando aperto o botão salvar aparece o seguinte erro:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ClientesDAO.gravar_DAO_Cli(ClientesDAO.java:78)
at CadastroClienteGraf$2.actionPerformed(CadastroClienteGraf.java:727)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
[color=red]Da uma olhada no codigo que os comentarios explica mais ou menos onde está os erros.
E agradeço se puderem ajudar… vlw[/color]
Meu codigo:
[code]public class CadastroClienteGraf extends JFrame {
private JTextField JTextFieldNome = null;
conexao conecta_cli = new conexao();
public CadastroClienteGraf() {
super();
conecta_cli.conecta();
initialize();
preencher_JTable();
}
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("EnigMais - Cadastro Cliente");
this.setIconImage(Toolkit.getDefaultToolkit().getImage("D:/Imagens/Simbolo sem fundo2.png"));
this.setBounds(new Rectangle(0, 0, 1192, 567));
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane.add(getJTextFieldNome(), null);
}
}
public JTextField getJTextFieldNome() {
if (JTextFieldNome == null) {
JTextFieldNome = new JTextField();
JTextFieldNome.setBounds(new Rectangle(213, 71, 207, 18));
JTextFieldNome.setEnabled(true);
JTextFieldNome.setText("");
JTextFieldNome.setFont(new Font("Dialog", Font.PLAIN, 11));
}
return JTextFieldNome;
}
private JButton getBotaoSalvarCliente() {
if (BotaoSalvarCliente == null) {
BotaoSalvarCliente = new JButton();
BotaoSalvarCliente.setBounds(new Rectangle(292, 430, 141, 24));
BotaoSalvarCliente.setEnabled(true);
BotaoSalvarCliente.setText("Salvar/Fechar");
BotaoSalvarCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClientesDAO CliDAO = new ClientesDAO();
CliDAO.teste(); // ESSE METODO IMPRIME VAZIO.. NÃO ESTÁ PEGANDO OS DADOS DO JTEXTFIELD PREENCHIDO PELO USUARIO.
// PERCEBAM QUE LOGO A BAIXO TEM UM METODO NESSA MESMA CLASS QUE SE CHAMA gravar_cliente_bd() E FUNCIONA PERFEITAMENTE
//NO ENTANTO ESSE METODO CliDAO.gravar_DAO_Cli(); QUE ESTÁ NA CLASS DAO N FUNCIONA.
CliDAO.gravar_DAO_Cli();
System.exit(0);
} }
}); }
return BotaoSalvarCliente;
}
public void gravar_cliente_bd(){
try {
String sqlinsert = "insert into cliente (nomeCliente) values (' "+JTextFieldNome.getText()+" ' )";
conecta_cli.statement.executeUpdate(sqlinsert);
} catch (SQLException e) {
e.printStackTrace();
}
}
}[/code]
[code]public class ClientesDAO { //CLASS QUE SUPONHO SER PROBLEMATICA.
ClienteJavaBean Cli_JB = new ClienteJavaBean();
conexao conecta_cli = new conexao();
public ClientesDAO(){
conecta_cli.conecta();
}
public void gravar_DAO_Cli(){
try {
String sqlinsert = "insert into cliente (nomeCliente) values ( ' "+Cli_JB.getJB_JTextFieldNome()+ " ')";
conecta_cli.statement.executeUpdate(sqlinsert);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Não está conseguindo salvar. Erro: "+e);
e.printStackTrace();
}
}
public void teste(){ //METODO SÓ PRA VERIFICAR O QUE ESTÁ SENDO CAPTURADO DO JTEXTFIELD PREENCHIDO PELO USUARIO
JOptionPane.showMessageDialog(null, Cli_JB.getJB_JTextFieldNome() );
}
}[/code]
[code]public class ClienteJavaBean implements java.io.Serializable {
private String JB_JTextFieldNome;
CadastroClienteGraf cadCliGrf = new CadastroClienteGraf();
public ClienteJavaBean() {
}
public String getJB_JTextFieldNome() {
String GF_JTextFieldNome = cadCliGrf.getJTextFieldNome().getText();
this.JB_JTextFieldNome = GF_JTextFieldNome;
return JB_JTextFieldNome;
}
public void setJB_JTextFieldNome(String jB_JTextFieldNome) {
JB_JTextFieldNome = jB_JTextFieldNome;
}
}[/code]
[code]public class conexao {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/EnigMaisBancoDDados";
private static final String usuario = "root";
private static final String senha = "minhasenha";
private Connection conexao;
public Statement statement;
public ResultSet resultset;
public boolean conecta() {
boolean result = true;
try {
Class.forName(driver);
conexao = DriverManager.getConnection(url, usuario, senha);
JOptionPane.showMessageDialog(null, "conectou");
} catch (ClassNotFoundException Driver) {
JOptionPane.showMessageDialog(null, "Driver não localizado: "+ Driver);
result = false;
} catch (SQLException Fonte) {
JOptionPane.showMessageDialog(null,
"Deu erro na conexão com a fonte de dados: " + Fonte);
result = false;
}
return result;
}
public void desconecta() {
boolean result = true;
try {
conexao.close();
JOptionPane.showMessageDialog(null, "banco fechado");
} catch (SQLException fecha) {
JOptionPane.showMessageDialog(null,
"Não foi possivel fechar o banco de dados : " + fecha);
result = false;
}
}
public void executeSQL(String sql) {
try {
statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
resultset = statement.executeQuery(sql);
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null,
"Não foi possivel executar o comando sql" + sqlex + "O sql passado foi" + sql);
}
}
}[/code]