Salvar jtextarea no BD [RESOLVIDO]

11 respostas
N

Olá Pessoal,

To precisando salvar os valores de uma textarea no postgre (esp.setInfoTA(infoTA.getText());), mas está dando erro, gostaria de saber se o set está incorreto, valeu.

11 Respostas

alexfe

Colega, post o log de erro que da console

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

at CadastroEspecie$1.actionPerformed(CadastroEspecie.java:85)

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.AWTEventMulticaster.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)

Valeu

alexfe

olha geralmente esse erro java.lang.NullPointerException acontece quando vc não inicializa o seu objeto, ou o valor da varial está null,

vc tem certeza que está instanciando o seu objeto esp ??

N

To sim, olha um pedaço ae.

final JButton salvarJB = new JButton();
		salvarJB.setIcon(SwingResourceManager.getIcon(CadastroEspecie.class, "/Img/Botões Padrões/Salva.png"));
		salvarJB.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent arg0) {

				Especie esp = new Especie();
				
				Date dt  = new Date();
		        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

				dtCadJT.setText(formato.format(dt));
				
				esp.setDs_especie(descJT.getText());
				esp.setInfoTA(infoTA.getText());
				esp.setDt_cadastro(dtCadJT.getText());
alexfe

olha só na linha 11

dtCadJT.setText(formato.format(dt));

está varial de objeto dtCadJT vc não está instanciando este objeto, de uma olhada

N

Ola Alexafe,

Meu problema ocorre em virtude da linha 14 [color=red]esp.setInfoTA(infoTA.getText());[/color], se comentar gravo normalmente no BD, se mudar de textarea para textfield tbm grava normalmente, o problema é realmente como gravar um textarea no BD.

alexfe

tente utilizar esp.setInfoTA(infoTA.getText().toString());

depois que vc seta a informação tenta imprimi no console para ver se aparece o que vc digitou no textArea
porque se a informação não estiver sendo atribuida a propriedade do objeto ira gerar erros

N

Fiz o que vc sugeriu, não da mais o erro anterior, mas continua não mandando para o BD e quando mando imprimir em tela tbm não aparece - System.out.println(infoTA), é como se não identificasse o que é digitado no textarea.

Obrigado pela força.

alexfe

Cara tenta imprimir o valor depois que foi setado para o objeto

esp.setInfoTA(infoTA.getText().toString()); System.out.println(esp.getInfoTA().toString()); // retorna valo que está no objeto ou System.out.println(infoTA.getText().toString()); // mostra valor do text area

N

Aléx, deixa eu abusar da sua boa vontade, da uma olhada no meu código abaixo, devo ta errando algo bem banal, me ajuda nessa.

import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.DebugGraphics;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JEditorPane;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
//import Entidades.Especie;

import com.swtdesigner.SwingResourceManager;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import com.swtdesigner.SwingResourceManager;

public class TelaCadastroEspecie extends JFrame {

	private JTextField dtCadJT;
	private JTextField descJT;
	private JTextField codigoJT;
	private JTextArea infoTA;
		
	private static EntityManagerFactory 
	fabricaDeEntidades = null;

	private static EntityManager gerenciador =  null;
	
	Especie localiza;
	
	public TelaCadastroEspecie() {
		super();
		setTitle("Cadastro de Espécie de Produto");
		getContentPane().setLayout(null);
		setBounds(100, 100, 497, 407);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		
		final JComponent separator_1 = DefaultComponentFactory.getInstance().createSeparator("");
		separator_1.setBounds(0, 100, 491, 9);
		getContentPane().add(separator_1);

		final JComponent separator_1_1 = DefaultComponentFactory.getInstance().createSeparator("");
		separator_1_1.setBounds(0, 103, 491, 9);
		getContentPane().add(separator_1_1);

		final JButton salvarJB = new JButton();
		salvarJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Salva.png"));
		salvarJB.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent arg0) {


					Especie esp = new Especie();

				try{
					Date dt  = new Date();
			        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
	
					dtCadJT.setText(formato.format(dt));
					
					esp.setDs_especie(descJT.getText());
					esp.setDs_info(infoTA.getText().toString());	
					//esp.setDs_info("xx");
					//esp.setInfoTA(infoTA.getText());
					esp.setDt_cadastro(dtCadJT.getText());
										
				}
				catch(Exception ex){}
				
				try{
					
					localiza = gerenciador.find(Especie.class, Integer.parseInt("9"));
					
					codigoJT.setText(String.valueOf(localiza.getCd_especie()));
									
					gerenciador.getTransaction().begin();
					gerenciador.persist(esp);
					gerenciador.getTransaction().commit();
				}
				catch(Exception ex){}
				
			}
		});
		salvarJB.setToolTipText("Salvar");
		salvarJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Salva.png"));
		salvarJB.setContentAreaFilled(false);
		salvarJB.setBorderPainted(false);
		salvarJB.setBounds(108, 33, 52, 52);
		getContentPane().add(salvarJB);

		final JButton excluirJB = new JButton();
		excluirJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Excluir.png"));
		excluirJB.setToolTipText("Excluir");
		//excluirJB.setIcon(SwingResourceManager.getIcon(CadastroEspecie.class, "/Img/Botões Padrões/Excluir.png"));
		excluirJB.setContentAreaFilled(false);
		excluirJB.setBorderPainted(false);
		excluirJB.setBounds(201, 33, 52, 52);
		getContentPane().add(excluirJB);

		final JButton SairJB = new JButton();
		SairJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Sair.png"));
		SairJB.setToolTipText("Sair");
		SairJB.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent arg0) {
				dispose();
				}
		});
//		SairJB.setIcon(SwingResourceManager.getIcon(CadastroEspecie.class, "/Img/Botões Padrões/Sair.png"));
		SairJB.setContentAreaFilled(false);
		SairJB.setBorderPainted(false);
		SairJB.setBounds(374, 33, 52, 52);
		getContentPane().add(SairJB);

		final JButton pesquisarJB = new JButton();
		pesquisarJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Pesquisar.png"));
		pesquisarJB.setToolTipText("Pesquisar");
//		pesquisarJB.setIcon(SwingResourceManager.getIcon(CadastroEspecie.class, "/Img/Botões Padrões/Pesquisar.png"));
		pesquisarJB.setContentAreaFilled(false);
		pesquisarJB.setBorderPainted(false);
		pesquisarJB.setBounds(18, 33, 52, 52);
		getContentPane().add(pesquisarJB);
		
		final JLabel codigoJL = new JLabel();
		codigoJL.setFont(new Font("Arial Narrow", Font.PLAIN, 14));
		codigoJL.setText("Código:");
		codigoJL.setBounds(17, 133, 37, 17);
		getContentPane().add(codigoJL);

		codigoJT = new JTextField();
		codigoJT.setEditable(false);
		codigoJT.setBounds(80, 133, 79, 20);
		getContentPane().add(codigoJT);

		descJT = new JTextField();
		descJT.setBounds(80, 159, 400, 20);
		getContentPane().add(descJT);
		
		final JLabel infoJL = new JLabel();
		infoJL.setFont(new Font("Arial Narrow", Font.PLAIN, 14));
		infoJL.setText("Informações:");
		infoJL.setBounds(19, 185, 228, 17);
		getContentPane().add(infoJL);
		
		final JButton limparJB = new JButton();
		limparJB.setIcon(SwingResourceManager.getIcon(TelaCadastroEspecie.class, "/Img/Botões Padrões/Limpar.png"));
//		limparJB.setIcon(SwingResourceManager.getIcon(CadastroEspecie.class, "/Img/Botões Padrões/Limpar.png"));
		limparJB.setToolTipText("Limpar");
		limparJB.setContentAreaFilled(false);
		limparJB.setBorderPainted(false);
		limparJB.setBounds(285, 33, 52, 52);
		getContentPane().add(limparJB);

		final JLabel dtCadJL = new JLabel();
		dtCadJL.setFont(new Font("Arial Narrow", Font.PLAIN, 14));
		dtCadJL.setText("Data Cadastro:");
		dtCadJL.setBounds(312, 354, 76, 17);
		getContentPane().add(dtCadJL);

		dtCadJT = new JTextField();
		dtCadJT.setBounds(394, 354, 87, 20);
		getContentPane().add(dtCadJT);
		
		descJT.requestFocus();

		final JLabel descJL = new JLabel();
		descJL.setFont(new Font("Arial Narrow", Font.PLAIN, 14));
		descJL.setText("Descrição:");
		descJL.setBounds(18, 161, 54, 17);
		getContentPane().add(descJL);

		setVisible(true);
		setResizable(false);
		setLocationRelativeTo(null);

		final TextArea infoTA = new TextArea();
		infoTA.setBounds(18, 208, 463, 141);
		getContentPane().add(infoTA);

		
	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger())
					showMenu(e);
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger())
					showMenu(e);
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});	
		
	}
	
	public static void main(String args[]) {
		
		fabricaDeEntidades = Persistence.createEntityManagerFactory("conexao");
		gerenciador = fabricaDeEntidades.createEntityManager();
		
		TelaCadastroEspecie frame = new TelaCadastroEspecie();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.swing.JTextField;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.Clob;
import static javax.persistence.GenerationType.SEQUENCE;
import java.io.Serializable;


@Entity
public class Especie {
	
	@Id
    @GeneratedValue(strategy=SEQUENCE,generator = "gerador")
	@SequenceGenerator(name="gerador", sequenceName = "gerador1", allocationSize=1)
	private int cd_especie;
	
	private String ds_especie;
	
	private String ds_info;
	
	private String dt_cadastro;

	public int getCd_especie() {
		return cd_especie;
	}

	public void setCd_especie(int cd_especie) {
		this.cd_especie = cd_especie;
	}

	public String getDs_especie() {
		return ds_especie;
	}

	public void setDs_especie(String ds_especie) {
		this.ds_especie = ds_especie;
	}

	public String getDs_info() {
		return ds_info;
	}

	public void setDs_info(String ds_info) {
		this.ds_info = ds_info;
	}

	public String getDt_cadastro() {
		return dt_cadastro;
	}

	public void setDt_cadastro(String dt_cadastro) {
		this.dt_cadastro = dt_cadastro;
	}


	
	
}

Valeu
N

Aléxafe,

Valeu pela força, um amigo meu resolveu, o problema estava em “[color=red]final TextArea infoTA = new TextArea();[/color]” que estava pondo após "[color=red]final JButton salvarJB = new JButton();[/color]"no final, carreguei para antes e deu certo.

Valeu pela força.

Criado 22 de março de 2011
Ultima resposta 24 de mar. de 2011
Respostas 11
Participantes 2