Erro java.lang.NullPointerException

6 respostas
G

Pessoal, estou iniciando no java e ao executar o programa abaixo quando clico no botão Gravar aparece esse erro abaixo, pesquisei sobre o erro mas não consegui identificar o que estou fazendo errado…
se alguém puder ajudar eu agradeço.

C:\jdk1.6.0_03\bin\java.exe  -classpath C:\jdk1.6.0_03\jre\lib\rt.jar;C:\jdk1.6.0_03\lib\tools.jar;C:\GERSON\Frame Frm001

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

at Frm001.insRegistros(Frm001.java:250)

at Frm001.btGravar_actionPerformed(Frm001.java:201)

at Frm001.access$100(Frm001.java:15)

at Frm001$2.actionPerformed(Frm001.java:106)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)

at java.awt.Component.processMouseEvent(Component.java:6038)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)

at java.awt.Component.processEvent(Component.java:5803)

at java.awt.Container.processEvent(Container.java:2058)

at java.awt.Component.dispatchEventImpl(Component.java:4410)

at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
			at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
			at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
			at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
			at java.awt.Container.dispatchEventImpl(Container.java:2102)
			at java.awt.Window.dispatchEventImpl(Window.java:2429)
			at java.awt.Component.dispatchEvent(Component.java:4240)
			at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
			at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
			at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
			at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
			at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
			at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
			at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Finished executing

/****************************************************************/
/*                      Frm001	                            */
/*                                                              */
/****************************************************************/
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.event.*;
/**
 * Summary description for Frm001
 *
 */
public class Frm001 extends JDialog
{
	// Variables declaration
	private JTabbedPane jTabbedPane1;
	private JPanel contentPane;
	//-----
	private JButton btGravar;
	private JButton btExcluir;
	private JPanel painelSul;
	//-----
	private JLabel lbNome;
	private JLabel lbEnder;
	private JTextField tfNome;
	private JTextField tfEnder;
	private JPanel painelA;
	//-----
	private JPanel painelB;
	//-----
	private String driver;
	private String url;
	private String userName;
	private String password;
	private Connection conn;
	// End of variables declaration


	public Frm001(Frame w)
	{
		super(w);
		initializeComponent();
		//
		// TODO: Add any constructor code after initializeComponent call
		//

		this.setVisible(true);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always regenerated
	 * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
	 * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
	 * to retrieve your design properly in future, before revising this method.
	 */
	private void initializeComponent()
	{
		jTabbedPane1 = new JTabbedPane();
		contentPane = (JPanel)this.getContentPane();
		//-----
		btGravar = new JButton();
		btExcluir = new JButton();
		painelSul = new JPanel();
		//-----
		lbNome = new JLabel();
		lbEnder = new JLabel();
		tfNome = new JTextField();
		tfEnder = new JTextField();
		painelA = new JPanel();
		//-----
		painelB = new JPanel();
		//-----
		ConfiguracaoFirebird cf = new ConfiguracaoFirebird();
		driver   = cf.getDRV();
		url      = cf.getUrl();
		userName = cf.getUserName();
		password = cf.getPassword();
		//
		// jTabbedPane1
		//
		jTabbedPane1.addTab("DadosBasicos", painelA);
		jTabbedPane1.addTab("Credito", painelB);
		jTabbedPane1.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e)
			{
				jTabbedPane1_stateChanged(e);
			}

		});
		//
		// contentPane
		//
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.add(painelSul, BorderLayout.SOUTH);
		contentPane.add(jTabbedPane1, BorderLayout.CENTER);
		//
		// btGravar
		//
		btGravar.setText("Gravar");
		btGravar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				btGravar_actionPerformed(e);
			}

		});
		//
		// btExcluir
		//
		btExcluir.setText("Excluir");
		btExcluir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				btExcluir_actionPerformed(e);
			}

		});
		//
		// painelSul
		//
		painelSul.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 20));
		painelSul.add(btGravar, 0);
		painelSul.add(btExcluir, 1);
		painelSul.setBorder(BorderFactory.createEtchedBorder());
		//
		// lbNome
		//
		lbNome.setText("Nome");
		//
		// lbEnder
		//
		lbEnder.setText("Endereço");
		//
		// tfNome
		//
		tfNome.setText("jTextField1");
		tfNome.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				tfNome_actionPerformed(e);
			}

		});
		//
		// tfEnder
		//
		tfEnder.setText("jTextField2");
		tfEnder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				tfEnder_actionPerformed(e);
			}

		});
		//
		// painelA
		//
		painelA.setLayout(null);
		painelA.setOpaque(false);
		addComponent(painelA, lbNome, 77,31,27,18);
		addComponent(painelA, lbEnder, 57,64,46,18);
		addComponent(painelA, tfNome, 107,29,100,22);
		addComponent(painelA, tfEnder, 106,63,100,22);
		//
		// painelB
		//
		painelB.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		painelB.setOpaque(false);
		//
		// Frm001
		//
		this.setTitle("Frm001 - Cadastro");
		this.setLocation(new Point(20, 20));
		this.setSize(new Dimension(460, 360));
	}

	/** Add Component Without a Layout Manager (Absolute Positioning) */
	private void addComponent(Container container,Component c,int x,int y,int width,int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}

	//
	// TODO: Add any appropriate code in the following Event Handling Methods
	//
	private void jTabbedPane1_stateChanged(ChangeEvent e)
	{
		System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
		// TODO: Add any handling code here

	}

	private void btGravar_actionPerformed(ActionEvent e)
	{
		//System.out.println("\nbtGravar_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here
		insRegistros();

	}

	private void btExcluir_actionPerformed(ActionEvent e)
	{
		System.out.println("\nbtExcluir_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here

	}

	private void tfNome_actionPerformed(ActionEvent e)
	{
		System.out.println("\ntfNome_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here

	}

	private void tfEnder_actionPerformed(ActionEvent e)
	{
		System.out.println("\ntfEnder_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here

	}

	//
	// TODO: Add any method code to meet your needs in the following area
	//


	/* Cria uma matriz de todas as JTextFields da tela */
	private JTextField[] campos() {
	   JTextField[] tf = {tfNome, tfEnder};
	   return tf;
	}


    private void insRegistros() {
       ConexaoFirebird firebird = new ConexaoFirebird();
       firebird.setDRV(driver);
       firebird.setURL(url);
       firebird.setUserName(userName);
       firebird.setPassword(password);

       firebird.conecta();

       JTextField[] tf = campos();
       try {
         String SQL = "insert into CAD001 (nome, ender) values (?, ?)";
         PreparedStatement ps = conn.prepareStatement(SQL);
         for(int i=0;i<tf.length;i++)
           ps.setString(i+1,tf[i].getText());
         ps.executeUpdate();
         ps.close();
       }catch(SQLException e) {
         e.printStackTrace();
       }
       firebird.desconecta();
    }






























//============================= Testing ================================//
//=                                                                    =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it.                            =//
//======================================================================//
	public static void main(String[] args)
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		try
		{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception ex)
		{
			System.out.println("Failed loading L&F: ");
			System.out.println(ex);
		}
		final JFrame w = new JFrame("Owner Window");
		JButton btn = new JButton("Show Dialog");
		btn.addActionListener(new java.awt.event.ActionListener() {
							public void actionPerformed(java.awt.event.ActionEvent e)
							{
								//-- Create a Frm001 --
								new Frm001(w);
								//-------------------
							}});
		JPanel p = new JPanel();
		p.add(btn);
		w.getContentPane().add(p);
		w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		w.setSize(500,360);
		w.setLocation(150,36);
		w.setVisible(true);
	}
//= End of Testing =


}

6 Respostas

B

Você precisa instanciar o objeto conn antes de usá-lo.

G

Esse objeto conn já está nesta outra classe…

import javax.swing.*;
import java.sql.*;

public class ConexaoFirebird {
	private String DRV;
	private String url;
	private String userName;
	private String password;
	private Connection conn;
	private Statement st;

	public boolean conecta() {
	  boolean result = true;
	  try {
	    Class.forName(DRV);
	    conn = DriverManager.getConnection(url, userName, password);
	    JOptionPane.showMessageDialog(null,"Conectou !!!");
	  }
	  catch(ClassNotFoundException erroClass) {
	  	mensagemErro(erroClass.getMessage());
	  	result = false;
	  }
	  catch(SQLException erroSQL) {
	    mensagemErro(erroSQL.getMessage());
	    result = false;
	  }
	  return result;
	}

	public void desconecta() {
		boolean result = true;
		try {
			conn.close();
		}
		catch(SQLException erroSQL) {
			mensagemErro(erroSQL.getMessage());
			result = false;
		}
	}

	public int regCount(String qry) {
		int result = 0;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(qry);
			rs.next();
			result = rs.getInt(1);
			st.close();
		}
		catch(SQLException sqlex) {
			mensagemErro(sqlex.getMessage());
		}
	    return result;
	}

	public int exeQuery(String qry) {
		int result = 0;
		try {
			st = conn.createStatement();
			result = st.executeUpdate(qry);
			st.close();
		}
		catch(SQLException sqlex) {
			mensagemErro(sqlex.getMessage());
		}
		return result;
	}

	public String getColumn(String qry) {
		String result = "";
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(qry);
			rs.next();
			result = "" + rs.getString(1);
	      st.close();
		}
		catch(SQLException sqlex) {
			mensagemErro(sqlex.getMessage());
		}
		return result;
	}

	public void getColumn(String qry, String[] reg) {
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(qry);
			rs.next();
			for (int i = 1; i <= reg.length; i++)
				reg[i-1] = "" + rs.getString(i);
			st.close();
		}
		catch(SQLException sqlex) {
			mensagemErro(sqlex.getMessage());
	  }
	}

	public void getColumn(String qry, String[][] reg, int regs) {
		try {
			int lin = 0;
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(qry);
			while (rs.next()) {
				for (int i = 0; i < regs; i++) {
					reg[lin][i] = "" + rs.getString(i+1);
				}
				lin++;
			}
		}
		catch(SQLException sqlex) {
			mensagemErro(sqlex.getMessage());
		}
	}

	public void setDRV(String valor) {
		DRV = valor;
	}

	public void setURL(String valor) {
		url = valor;
	}

	public void setUserName(String valor) {
		userName = valor;
	}

	public void setPassword(String valor) {
		password = valor;
	}

	private void mensagemErro(String msg) {
		JOptionPane.showMessageDialog(
		  null,
	    msg,
	    "Erro",
	    JOptionPane.ERROR_MESSAGE);
	}
}
fiaux

Sim, é verdade, você precisa fazer isso, isso se você quiser usar o objeto conn. Digo isso pois, pelo o que entendi, você criou uma classe que encapsula conn, a ConexaoFirebird, então pra que usar conn na outra classe? Use a classe ConexaoFirebird. Você criou um esquema para acessar o banco através dele e não usou.

B

Pode até estar também em outra classe, mas o teu programa está usando outro. Olhe nas linhas 37 e 250.

G

é que eu lí que num projeto em que nenhuma tecnologia de ORM é utilizada deve ser empregado pelo menos o DAO, é isso que estou tentando mas sem sucesso…

B

Primeiro aprenda a programar, depois aprenda Java, e depois, beeem depois, sobre Java EE e sobre como persistir os dados com frameworks ORM e padrões de projeto.

O teu problema é de escopo de variável, não de arquitetura de sistemas.

Criado 9 de agosto de 2008
Ultima resposta 10 de ago. de 2008
Respostas 6
Participantes 3