Duvidas

Pessoal, seguinte to tentando fazer com que a ação do botão ele pegue os dados em uma
textfield, e envie para o banco de dados, ou seja, é um insert simples, so que naum sei o que eu fiz que dá erro de java.lang.NullException, alguem poderia me ajudar?

O código é esse:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;

import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
/*
 * Created on 04/05/2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Administrador
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Fornecedores extends JInternalFrame implements ActionListener {

	private javax.swing.JPanel jContentPane = null;

	private JToolBar jToolBar = null;
	private JButton jButton = null;
	private JButton jButton1 = null;
	private JButton jButton2 = null;
	private JButton jButton3 = null;
	private JButton jButton4 = null;
	private JButton jButton5 = null;
	private JPanel jPanel = null;
	private JLabel jLabel = null;
	private JTextField jTextField = null;
	private JLabel jLabel1 = null;
	private JTextField jTextField1 = null;
	private JLabel jLabel2 = null;
	private JTextField jTextField2 = null;
	private JLabel jLabel3 = null;
	private JTextField jTextField3 = null;
	private JLabel jLabel4 = null;
	private JTextField jTextField4 = null;
	private JLabel jLabel5 = null;
	private JTextField jTextField5 = null;
	private Conexao Con=new Conexao();
	private static Connection con;
	/**
	 * 
	 */
	public Fornecedores() {
		super();
		// TODO Auto-generated constructor stub
		initialize();
	}

	/**
	 * @param arg0
	 */
	public Fornecedores(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
		initialize();
	}

	/**
	 * @param arg0
	 * @param arg1
	 */
	public Fornecedores(String arg0, boolean arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
		initialize();
	}

	/**
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 */
	public Fornecedores(String arg0, boolean arg1, boolean arg2) {
		super(arg0, arg1, arg2);
		// TODO Auto-generated constructor stub
		initialize();
	}

	/**
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	public Fornecedores(String arg0, boolean arg1, boolean arg2, boolean arg3) {
		super(arg0, arg1, arg2, arg3);
		// TODO Auto-generated constructor stub
		initialize();
	}

	/**
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @param arg4
	 */
	public Fornecedores(String arg0, boolean arg1, boolean arg2, boolean arg3,
			boolean arg4) {
		super(arg0, arg1, arg2, arg3, arg4);
		// TODO Auto-generated constructor stub
		initialize();
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * This method initializes jToolBar	
	 * 	
	 * @return javax.swing.JToolBar	
	 */    
	private JToolBar getJToolBar() {
		if (jToolBar == null) {
			jToolBar = new JToolBar();
			jToolBar.setSize(420, 33);
			jToolBar.setLocation(2, 3);
			jToolBar.add(getJButton());
			jToolBar.add(getJButton1());
			jToolBar.add(getJButton2());
			jToolBar.add(getJButton3());
			jToolBar.add(getJButton4());
			jToolBar.add(getJButton5());
		}
		return jToolBar;
	}
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/filenew.png")));
			jButton.setToolTipText("Novo");
		}
		return jButton;
	}
	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/filesave.png")));
			jButton1.setToolTipText("Salvar");
			jButton1.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
					try
					{
						Conexao.conectar().createStatement().executeUpdate("INSERT INTO FORNECEDORES VALUES ('"+jTextField.getText()+"', '"+ jTextField1.getText() +"', '"+jTextField2.getText()+"', '"+jTextField3.getText()+"', '"+jTextField4.getText()+"', '"+jTextField5.getText()+"')" );
						JOptionPane.showMessageDialog(null,"Salvo com sucesso");
					}
					catch (Exception error){
						System.out.println(error);
					}
					/*}*/
				}
			});


		}
		return jButton1;
	}
	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/edit.png")));
			jButton2.setToolTipText("Alterar");
		}
		return jButton2;
	}
	/**
	 * This method initializes jButton3	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton3() {
		if (jButton3 == null) {
			jButton3 = new JButton();
			jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/filefind.png")));
			jButton3.setToolTipText("Consultar");
		}
		return jButton3;
	}
	/**
	 * This method initializes jButton4	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton4() {
		if (jButton4 == null) {
			jButton4 = new JButton();
			jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/removecomment.png")));
			jButton4.setToolTipText("Excluir");
		}
		return jButton4;
	}
	/**
	 * This method initializes jButton5	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getJButton5() {
		if (jButton5 == null) {
			jButton5 = new JButton();
			jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/exit.png")));
			jButton5.setToolTipText("Sair Cadastro");
			jButton5.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
					setVisible(false); // TODO Auto-generated Event stub actionPerformed()
				}
			});
		}
		return jButton5;
	}
	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */    
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jLabel = new JLabel();
			jLabel1 = new JLabel();
			jLabel2 = new JLabel();
			jLabel3 = new JLabel();
			jLabel4 = new JLabel();
			jLabel5 = new JLabel();
			jPanel.setLayout(null);
			jPanel.setLocation(28, 64);
			jPanel.setSize(362, 271);
			jPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
			jLabel.setText("Código:");
			jLabel.setLocation(10, 16);
			jLabel.setSize(49, 20);
			jLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jLabel1.setText("Nome:");
			jLabel1.setSize(49, 20);
			jLabel1.setLocation(10, 56);
			jLabel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jLabel2.setText("Endereço:");
			jLabel2.setSize(63, 20);
			jLabel2.setLocation(10, 96);
			jLabel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jLabel3.setText("Fone:");
			jLabel3.setSize(49, 20);
			jLabel3.setLocation(10, 136);
			jLabel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jLabel4.setText("Responsável:");
			jLabel4.setLocation(10, 176);
			jLabel4.setSize(81, 20);
			jLabel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jLabel5.setText("Especialidade:");
			jLabel5.setLocation(10, 216);
			jLabel5.setSize(88, 20);
			jLabel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
			jPanel.add(jLabel, null);
			jPanel.add(getJTextField(), null);
			jPanel.add(jLabel1, null);
			jPanel.add(getJTextField1(), null);
			jPanel.add(jLabel2, null);
			jPanel.add(getJTextField2(), null);
			jPanel.add(jLabel3, null);
			jPanel.add(getJTextField3(), null);
			jPanel.add(jLabel4, null);
			jPanel.add(getJTextField4(), null);
			jPanel.add(jLabel5, null);
			jPanel.add(getJTextField5(), null);
		}
		return jPanel;
	}
	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField() {
		if (jTextField == null) {
			jTextField = new JTextField();
			jTextField.setLocation(10, 36);
			jTextField.setSize(120, 20);
		}
		return jTextField;
	}
	/**
	 * This method initializes jTextField1	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField1() {
		if (jTextField1 == null) {
			jTextField1 = new JTextField();
			jTextField1.setSize(240, 20);
			jTextField1.setLocation(10, 76);
		}
		return jTextField1;
	}
	/**
	 * This method initializes jTextField2	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField2() {
		if (jTextField2 == null) {
			jTextField2 = new JTextField();
			jTextField2.setSize(240, 20);
			jTextField2.setLocation(10, 116);
		}
		return jTextField2;
	}
	/**
	 * This method initializes jTextField3	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField3() {
		if (jTextField3 == null) {
			jTextField3 = new JTextField();
			jTextField3.setLocation(10, 156);
			jTextField3.setSize(120, 20);
		}
		return jTextField3;
	}
	/**
	 * This method initializes jTextField4	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField4() {
		if (jTextField4 == null) {
			jTextField4 = new JTextField();
			jTextField4.setSize(240, 20);
			jTextField4.setLocation(10, 196);
		}
		return jTextField4;
	}
	/**
	 * This method initializes jTextField5	
	 * 	
	 * @return javax.swing.JTextField	
	 */    
	private JTextField getJTextField5() {
		if (jTextField5 == null) {
			jTextField5 = new JTextField();
			jTextField5.setSize(240, 20);
			jTextField5.setLocation(10, 236);
		}
		return jTextField5;
	}
                	public static void main(String[] args) {
	}
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setMaximizable(true);
		this.setClosable(true);
		this.setTitle("Controle de Fornecedores");
		this.setSize(435, 390);
		this.setContentPane(getJContentPane());
		this.setVisible(true);
	}
	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private javax.swing.JPanel getJContentPane() {
		if(jContentPane == null) {
			jContentPane = new javax.swing.JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJToolBar(), null);
			jContentPane.add(getJPanel(), null);
		}
		return jContentPane;
	}
}  //  @jve:decl-index=0:visual-constraint="10,10"

Qual a linha que está dando esse NPE? Ou melhor, poste o trecho de código, pois não podemos ver a linha. :roll:

private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/filesave.png")));
			jButton1.setToolTipText("Salvar");
			jButton1.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
					try
					{
						Conexao.conectar().createStatement().executeUpdate("INSERT INTO FORNECEDORES VALUES ('"+jTextField.getText()+"', '"+ jTextField1.getText() +"', '"+jTextField2.getText()+"', '"+jTextField3.getText()+"', '"+jTextField4.getText()+"', '"+jTextField5.getText()+"')" );
						JOptionPane.showMessageDialog(null,"Salvo com sucesso");
					}
					catch (Exception error){
						System.out.println(error);
					}
					/*}*/
				}
			});


		}
		return jButton1;
	}

Tenta inicializar os botoes dentro do construtor, antes de tudo. não só os botões, mais todos componentes.

[quote=“Dumpa”][code]
private JButton getJButton1() {
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/16x16/filesave.png")));
jButton1.setToolTipText(“Salvar”);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try
{
Conexao.conectar().createStatement().executeUpdate(“INSERT INTO FORNECEDORES VALUES (’”+jTextField.getText()+"’, ‘"+ jTextField1.getText() +"’, ‘"+jTextField2.getText()+"’, ‘"+jTextField3.getText()+"’, ‘"+jTextField4.getText()+"’, ‘"+jTextField5.getText()+"’)" );
JOptionPane.showMessageDialog(null,“Salvo com sucesso”);
}
catch (Exception error){
System.out.println(error);
}
/}/
}
});

	}
	return jButton1;
}

[/code][/quote]

Ok, mas quando é lançada a Null Pointer no console, ele diz qual as linhas… poste a saída da exception.

ps: algo me diz que tem a ver com essa conexão… :roll:

Vc acerto na mosca, tem a haver com a minha conexão, naum sei o que acontece que toda a minha conexao dá esse erro seguinte:

IWAV0048I Java Bean Conexao started with null constructor

Refiz a minha conexão um monte de vezes naum sei o que pode de estar errado, vou postar aqui o código da conexão:



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




public class Conexao {
  /**
   * Objeto responsável por buscar as configurações do banco de dados no arquivo de  properties. 
   */

       
  private static Connection connection; 
  private static Conexao instance ;
  private static Statement statement;
  private static String dbUrl = null;
  private static String user;
  private static String pws; 
  private String msg ="";
  
  public Conexao()  { 
    getConnection();
  }
  /**
   * Método responsavel por realizar a conexao do usuario ao banco de dados.
   * @param usuario Nickname do usuario
   * @param senha   Senha do usuario
   * @return Retorna uma String informando se a conexão foi concluída com sucesso ou não.
   */
  public String conexao(String usuario, String senha )  {
  	
  	Conexao conn = new Conexao();
  	msg = conn.conexao(usuario,senha);
    user = usuario;
    pws = senha;
       
    try {
      Class.forName("com.mysql.jdbc.Driver");
      connection=DriverManager.getConnection(dbUrl, "root", "");
      
      statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      
      msg = "Vc está conectado";
    } catch (ClassNotFoundException e){
      msg = e.toString();
      connection = null;
    } catch (SQLException e ){
      connection=null;
      
      
      if (e.getErrorCode() == 1017){
          /*Usuairio ou Senha recusado pelo servidor. */
          msg = "Usuario ou senha invalido";
      }
       else if(e.getErrorCode() == 28001){
          /*Senha Expirada */
          msg = "0";      
      }else{
          msg = e.getMessage();
      }
    } 
    return msg; 
  }
  /**
   * Método que retorna a conexão para usuário já conectado. 
   * @return Retorna a Conexao
   */
  public static Connection getConnection(){
    return connection;
  }
  
  /**
   * Método que commita a ações de inserção e exclusão.
   * @throws java.sql.SQLException exceções de SQL
   */
  public void commit() throws SQLException{
    connection.commit();
  }
  /**
   * Método que desfaz a ações de inserção e exclusão.
   * @throws java.sql.SQLException exceções de SQL
   */
  public void rollback() throws SQLException{
    connection.rollback();
  }
  
  /**
   * Metodo que ativa e desativa o autocommit que para false.
   * @param autoCommit valor para o autocommit
   * @throws java.sql.SQLException exceções de SQL
   */
  public void setAutoCommit(boolean autoCommit)throws SQLException{
    connection.setAutoCommit(autoCommit);
  }
  /**
   * Método que executa as Query tipo (Select) das camadas de negocio.
   * @param sql  comando sql enviada das classes de negocio 
   * @return Retornando ResultSet
   * @throws java.sql.SQLException exceções de SQL
   */
  public ResultSet  executeQuery(String sql) throws SQLException{
    return statement.executeQuery(sql);
  }
  /**
    * Método que executa as Query tipo (Update, Delete e Insert ) das camadas de negocio.
   * @param sql  comando sql enviada das classes de negocio 
   * @return retorna o sucesso ou erro
   * @throws java.sql.SQLException exceções de SQL
   */
  public int executeUpdate(String sql) throws SQLException{
    return statement.executeUpdate(sql);
  }
  
  /**
   * Método que segura conexão do usuário no servido, para que não espire.
   * @param event evento da conexão
   */
  
  protected void finalizer(){
    try{
      setUser(null);
      setPws(null);
      statement.close();
      connection.close();
    } catch (SQLException e){
    e.printStackTrace();       
    }
  }

  /**
   * Método que retorna a ConnectionDB instaciada.
   * @return retorna a conexao
   */
 public static Conexao getInstance(){
   if (instance == null){
   instance = new   Conexao();
   }
   return instance;
 }

  /**
   * Método que recebe o usuario.
   * @param user nickname do usuario
   */
  public void setUser(String user) {
    this.user = user;
  }
 
  /**
   * Método que recebe a senha do usuario.
   * @param pws senha do usuário
   */
  public void setPws(String pws) {
    this.pws = pws;
  }

  

  public void fechar()throws Exception  {

     finalizer();
  }
  
}