Exception in thread "AWT-EventQueue-0"

4 respostas
AITech_IX

Olá pessoal, tudo blz??

O seguinte erro:
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at cap12.SimpleGui1.actionPerformed(SimpleGui1.java:25)

aparece porque executo o código baixo…ele é muuuito simples, só muda o texto do botao quando o mesmo é apertado. Diz que não tem nenhum erro de sintaxe…apenas quando eu clico no botão é que aparece o erro acima…alguém suspeita de algo???
muito obrigado!!! :slight_smile:

import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1 implements ActionListener{
	JButton button;
	
	public static void main(String[] args){
		SimpleGui1 gui = new SimpleGui1();
		gui.go();
	}
	
	public void go(){
		JFrame frame = new JFrame();
		JButton button = new JButton("click me");
				
		button.addActionListener(this);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(button); //adiciona o botao ao content pane do JFrame
		frame.setSize(100,100);
		frame.setVisible(true);
	}
	
	public void actionPerformed(ActionEvent event){
		button.setText("I've been clicked!!");
	}
}

4 Respostas

alberthy
package gui;

import javax.swing.<em>;

import java.awt.event.</em>;

public class SimpleGui1 implements ActionListener{
[b] JButton button = new JButton("click me");  [/b]
   
 public static void main(String[] args){  
     SimpleGui1 gui = new SimpleGui1();  
     gui.go();       }  
   
 public void go(){  
	 
     JFrame frame = new JFrame();  
               
     button.addActionListener(this);  
     
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     frame.getContentPane().add(button); //adiciona o botao ao content pane do JFrame  
     frame.setSize(100,100);  
     frame.setVisible(true);  
 }  
   
 public void actionPerformed(ActionEvent event){ 
	 
	
     button.setText("I've been clicked!!");
	 
 }

}

AITech_IX

Funcionou Albert, obrigado!

Mas você saberia me explicar o por quê??? :oops:

ViniGodoy

A variável button que você cria na linha 4 não é a mesma variável button criada na linha 13.

Para corrigir aquele seu programa inicial, troque a linha 13 por:

Se você colocar o nome da classe antes, estará criando uma nova variável, com escopo local, e nome idêntico a criada fora.

AITech_IX

Perfeitamente entendido!

Obrigado!

Criado 1 de setembro de 2010
Ultima resposta 1 de set. de 2010
Respostas 4
Participantes 3