Como verificar se um botão está sendo pressionado em outra classe?

Tenho uma classe que verifica se um botão de uma outra classe está sendo pressionado da seguinte forma:

Classe classeDoBotao = new Classe();
if(classeDoBotao.JButton.isEnabled()) {
      //Faz alguma coisa
}

Mas ele me retorna essa Exception:

java.lang.NullPointerException.

Alguém sabe a solução pra isso?

1 curtida

Teria como você debugar este erro, e nos mostrar aonde o erro ocorre com informações mais precisas ? Ou nos mostrar a parte do código da classe em que você está instanciando ?

Um erro de NullPointerException ocorre quando você refere-se á uma instância de objeto nulo. Quando você tenta passar uma das suas variáveis como nula, mas o código tenta usar como se não fosse.

1 curtida

Primeiro: isEnabled() verifica se o botão está habilitado, isto é, se o usuário consegue interagir com ele. para verificar se está pressionado, você usa botao.getModel().isPressed().

Segundo: Você sempre está criando um novo objeto da classe com a seguinte instrução Classe objeto = new Classe(); não está certo, você tem que usar a instância que você já tem. Lembre-se, se usou a instrução new, então você criou um novo objeto.

Terceiro: se no código abaixo está acontecendo NullPointerException, então é porque ou o objeto ou o atributo não foram inicializados. No seu caso você sempre está inicializando um novo objeto, o que está errado.

if (objeto.atributo.metodo()) {
      // Faz alguma coisa
}

Quarto: Posta o código completo dos fontes.

3 curtidas

Vou deixar as classes que estão dando problema pra você analisar, se ficar muito confuso pode perguntar que respondo, o meu problema é apenas a classe PC que da o erro ao verificar se o botão está habilitado ou não.

Classe Jogo:

package br.paulo.jogo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Jogo extends JFrame {
	JButton btnCentro, btnSuperior, btnInferior, btnEsquerda, btnDireita, btnSuperEsquerda, btnSuperDireita, btnInfeEsquerda, btnInfeDireita;
	boolean click = false, Vez = false;
	public void Jogo() {
		//JFrame
		this.setTitle("Jogo");
		this.setSize(217,240);
		this.setLocationRelativeTo(null);
		this.setLayout(null);
		//
		
		//Button centro
		btnCentro = new JButton();
		btnCentro.setBounds(75,75,50,50);
		ActionListener actCentro = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(!click) {
					String pathImgX = "/resource/X.jpg";
					btnCentro.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
					click = false;
					btnCentro.setEnabled(false);
					PC p = new PC();
					p.pc();
				}
			}
		};
		btnCentro.addActionListener(actCentro);
		//
		
		//Button superior
				btnSuperior = new JButton();
				btnSuperior.setBounds(75,0,50,65);
				ActionListener actSuperior = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnSuperior.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnSuperior.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnSuperior.addActionListener(actSuperior);
				//
				
				//Button inferior
				btnInferior = new JButton();
				btnInferior.setBounds(75,135,50,65);
				ActionListener actInferior = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnInferior.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnInferior.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnInferior.addActionListener(actInferior);
				//
				
				//Button esquerda
				btnEsquerda = new JButton();
				btnEsquerda.setBounds(0,75,65,50);
				ActionListener actEsquerda = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnEsquerda.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnEsquerda.addActionListener(actEsquerda);
				//
				
				//Button direita
				btnDireita = new JButton();
				btnDireita.setBounds(135,75,65,50);
				ActionListener actDireita = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnDireita.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnDireita.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnDireita.addActionListener(actDireita);
				//
				
				//Button superior equerda
				btnSuperEsquerda = new JButton();
				btnSuperEsquerda.setBounds(0,0,65,65);
				ActionListener actSuperEsquerda = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnSuperEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnSuperEsquerda.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnSuperEsquerda.addActionListener(actSuperEsquerda);
				//
				
				//Button superior direita
				btnSuperDireita = new JButton();
				btnSuperDireita.setBounds(135,0,65,65);
				ActionListener actSuperDireita = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnSuperDireita.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnSuperDireita.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnSuperDireita.addActionListener(actSuperDireita);
				//
				
				//Button inferior esquerda
				btnInfeEsquerda = new JButton();
				btnInfeEsquerda.setBounds(0,135,65,65);
				ActionListener actInfeEsquerda = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnInfeEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnInfeEsquerda.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnInfeEsquerda.addActionListener(actInfeEsquerda);
				//
				
				//Button inferior direita
				btnInfeDireita = new JButton();
				btnInfeDireita.setBounds(135,135,65,65);
				ActionListener actInfeDireita = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!click) {
							String pathImgX = "/resource/X.jpg";
							btnInfeDireita.setIcon(new ImageIcon(getClass().getResource((pathImgX))));
							click = false;
							btnInfeDireita.setEnabled(false);
							PC p = new PC();
							p.pc();
						}
					}
				};
				btnInfeDireita.addActionListener(actInfeDireita);
				//
				
		//Imagem do jogo
		JLabel imgGame = new JLabel();
		imgGame.setSize(200,200);
		String pathImgJogo = "/resource/jogo.jpg";
		imgGame.setIcon(new ImageIcon(getClass().getResource((pathImgJogo))));
		//
		
		
		//JFrame
		this.add(btnCentro);
		this.add(btnSuperior);
		this.add(btnInferior);
		this.add(btnEsquerda);
		this.add(btnDireita);
		this.add(btnSuperEsquerda);
		this.add(btnSuperDireita);
		this.add(btnInfeEsquerda);
		this.add(btnInfeDireita);
		this.add(imgGame);
		this.setVisible(true);
		this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
		//
	}
}

Classe PC (Onde está dando o problema com os IFs):

package br.paulo.jogo;

import javax.swing.ImageIcon;

public class PC extends Jogo {
	
	public void pc()  {
		
		int num = (int) (0 + Math.random() * (9 - 0));
		
		if(btnCentro.isEnabled() && num == 0) {
			String pathImgO = "/resource/O.jpg";
			btnCentro.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnCentro.setEnabled(false);
		}
		if(btnSuperior.isEnabled() && num == 1) {
			String pathImgO = "/resource/O.jpg";
			btnSuperior.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnSuperior.setEnabled(false);
		}
		if(btnInferior.isEnabled() && num == 2) {
			String pathImgO = "/resource/O.jpg";
			btnInferior.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnInferior.setEnabled(false);
		}
		if(btnEsquerda.isEnabled() && num == 3) {
			String pathImgO = "/resource/O.jpg";
			btnEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnEsquerda.setEnabled(false);
		}
		if(btnDireita.isEnabled() && num == 4) {
			String pathImgO = "/resource/O.jpg";
			btnDireita.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnDireita.setEnabled(false);
		}
		if(btnSuperEsquerda.isEnabled() && num == 5) {
			String pathImgO = "/resource/O.jpg";
			btnSuperEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnSuperEsquerda.setEnabled(false);
		}
		if(btnSuperDireita.isEnabled() && num == 6) {
			String pathImgO = "/resource/O.jpg";
			btnSuperDireita.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnSuperDireita.setEnabled(false);
		}
		if(btnInfeEsquerda.isEnabled() && num == 7) {
			String pathImgO = "/resource/O.jpg";
			btnInfeEsquerda.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnInfeEsquerda.setEnabled(false);
		}
		if(btnInfeDireita.isEnabled() && num == 8) {
			String pathImgO = "/resource/O.jpg";
			btnInfeDireita.setIcon(new ImageIcon(getClass().getResource((pathImgO))));
			btnInfeDireita.setEnabled(false);
		}
	}
}

Acho que falta um super() no construtor de PC, pois seus componentes (botões etc) são criados no construtor da classe Jogo.

public class PC extends Jogo {

   public PC() { // Construtor
    super();
   }
}

Acabei de ver que não há construtores em suas classes:

public void Jogo() {/*...*/}  // Isso não é um construtor

public Jogo() {/*...*/}  // Isso é um construtor

Sua aplicação chega a executar? (pelo visto não)

1 curtida

Não usei construtores, apenas usei a classe extends para poder usar os botões da classe Jogo, mas ja tentei com construtores também e o mesmo erro persiste.

Poxa, me ajuda ai pessoal pf

Você declarou o construtor da classe Jogo como sendo um método void, está errado, construtores não possuem retorno pois o retorno é a instância da classe.

É só você trocar

public void Jogo() {

por

public Jogo() {

1 curtida

Vlwww e eu quebrando a cabeça por uma coisa tão boba