[RESOLVIDO] Ajuda com Eventos e Botoes

4 respostas
cle.darsie

Ola pessoal,

Seguinte, criei um código que le um JTextField, inverte a palavra digitada e mostra em outro JTextField.

Só que nao esta pegando a palavra digitada está dando um erro de Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

Se eu digitar com o Scanner ele funciona e inverte, se eu tento pegar do JTextField da erro.

Vou postar meu código aqui, por favor, deem uma olhada... questao que caiu na prova de Java q tive hj, fiz exatamente isso na prova rsrs.. Acho q 1 ponto eu ganho né? rs

MainExibir

public class MainExibir {
	public static void main(String args[]){
		new ExibirNome();
	}
}

ExibirInverso

import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ExibirInverso extends JFrame {
	private JButton button1, button2;
	private JLabel label1, label2;
	private JTextField field1, field2;
	private JPanel panel1, panel2;
	private TratadorExibir ouvinte;
	
	public ExibirInverso(){
		button1 = new JButton("Inveter");
		button2 = new JButton("Sair");
		label1 = new JLabel("Nome: ");
		label2 = new JLabel("Nome Invertido: ");
		field1 = new JTextField(10);
		field2 = new JTextField(10);
		field2.setEditable(false);
		panel1 = new JPanel(new GridLayout(2,1,10,50));
		panel2 = new JPanel(new GridLayout(1,1,10,10));
		ouvinte = new TratadorExibir(button1, button2);
		
		panel1.add(label1);
		panel1.add(field1);
		panel1.add(button1);
		panel1.add(button2);
		panel2.add(label2);
		panel2.add(field2);
		button1.addActionListener(ouvinte);
		button2.addActionListener(ouvinte);
		add(panel1);
		add(panel2);
		
		setSize(300,300);
		setLayout(new FlowLayout(FlowLayout.CENTER,0,50));
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);		
	}
	public JTextField getNome(){
		return field1;
	}
	public void setNome(JTextField nome){
		field2 = nome;
	}
}

TratadorExibir

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class TratadorExibir implements ActionListener{
	private JButton botao1, botao2;
	private ExibirInverso nome;
	private String tmp;
	
	public TratadorExibir(JButton btmp1, JButton btmp2){
		botao1 = btmp1;
		botao2 = btmp2;
		tmp = "";
	}
	
	public void actionPerformed(ActionEvent e){
		if (e.getSource() == botao1){
			tmp = nome.getNome().getText();
			StringBuffer sb = new StringBuffer(tmp);
			System.out.println(sb.reverse());
			//nome.setNome(setText(tmp5.reverse())); //Precisa converter para passar para um JTextField	
		}	
		if (e.getSource() == botao2){
			System.exit(0);
		}
	}
}

Erro que aparece qdo eu clico em inverter

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at codigos.TratadorExibir.actionPerformed(TratadorExibir.java:20)
	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:6289)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
	at java.awt.Component.processEvent(Component.java:6054)
	at java.awt.Container.processEvent(Container.java:2041)
	at java.awt.Component.dispatchEventImpl(Component.java:4652)
	at java.awt.Container.dispatchEventImpl(Container.java:2099)
	at java.awt.Component.dispatchEvent(Component.java:4482)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
	at java.awt.Container.dispatchEventImpl(Container.java:2085)
	at java.awt.Window.dispatchEventImpl(Window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4482)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
	at java.awt.EventQueue.access$000(EventQueue.java:85)
	at java.awt.EventQueue$1.run(EventQueue.java:603)
	at java.awt.EventQueue$1.run(EventQueue.java:601)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$2.run(EventQueue.java:617)
	at java.awt.EventQueue$2.run(EventQueue.java:615)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Tenho certeza q é uma coisa mto besta, mas nao to achando oq é...
To tendo um problema parecido com um outro código q eu to fazendo, ja postei tbm aqui no fórum, mas ninguem conseguiu ajudar..

Espero q com esse vcs consigam...

Valeu galera.

4 Respostas

Jesuino_Master

Você não instancia, não seta a referência, disto:

private ExibirInverso nome;

E tenta acessar ele aqui:

tmp = nome.getNome().getText();

Em outras palacras, faltou você setar o “nome” dentro da classe “TratadorExibir”. Você pode setar no construtor:

public TratadorExibir(JButton btmp1, JButton btmp2, ExibirInverso exibirInverso){  
        botao1 = btmp1;  
        botao2 = btmp2;  
        tmp = "";  
        nome = exibirInverso;
    }

E quando instanciar:

ouvinte = new TratadorExibir(button1, button2, this);

deve funcionar…

[]'s

cle.darsie

Ola Jesuino Master,

Muito obrigado pela sua explicaçao!
Simplesmente abriu minha mente agora…
Era exatamente esse o erro. Agora esta dando certo.

Isso é uma das coisas q nao se aprendem na faculdade, tem q correr atras mesmo.

Muito obrigado pela ajuda.
Agora preciso só fazer a outra parte, q é pegar aquela resposta invertida, e inserir no segundo JTextField que esta em branco, esperando pela resposta.

Vou tentando aqui…
Se mais alguem puder me ajudar com isso, eu agradeco mto!

Bruno_Ferreira1

cle.darsie:
Ola Jesuino Master,

Muito obrigado pela sua explicaçao!
Simplesmente abriu minha mente agora…
Era exatamente esse o erro. Agora esta dando certo.

Isso é uma das coisas q nao se aprendem na faculdade, tem q correr atras mesmo.

Muito obrigado pela ajuda.
Agora preciso só fazer a outra parte, q é pegar aquela resposta invertida, e inserir no segundo JTextField que esta em branco, esperando pela resposta.

Vou tentando aqui…
Se mais alguem puder me ajudar com isso, eu agradeco mto!

no segundo caso, voce pode simplesmente mudar o método da classe ExibirInverso:

public void setNome(JTextField nome){ field2 = nome; }

pra ele receber uma String, ao invés de um JTextField:

public void setNome(String nome){ field2.setText(nome); }

cle.darsie

Olá Bruno Ferreira…

Muito obrigado pela sua dica, mais uma coisa que eu aprendi!
Estou quase no rumo certo, é só começar a enxergar as coisas com mais atenção.

Ficou perfeito.

Muito obrigado pela ajuda.

Criado 31 de março de 2011
Ultima resposta 1 de abr. de 2011
Respostas 4
Participantes 3