Boa tarde, em primeiro lugar sei que Swing é uma ferramenta antiga, mas quero saber como funciona. E acho que minha dúvida é mais de POO
Estou tentando fazer um JButton trocar o JPanel de um JFrame.
Tenho uma classe Handler que implementa a ActionListener e nela eu instancio um dos JPanels (acho que esse é o problema)
Estou recebendo o StackOverflowError, porque acho que a classe fica sendo instanciada várias vezes e que estou adicionando o pnlCad em um objeto diferente do original.
Qual seria uma solução pra isso? Sou iniciante e me perdi.
Tela:
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.JFrame;
public class Tela extends JFrame {
private PainelInicial pnlIni;
private PainelCadastro pnlCad;
private PainelDados pnlDados;
//private Container containerTela;
public Tela() throws HeadlessException {
initTela();
pnlIni = new PainelInicial();
pnlCad = new PainelCadastro();
pnlDados = new PainelDados();
getContentPane().add(pnlIni);
pack();
setVisible(true);
}
// private Container getContPane(){
// containerTela = new Container();
// containerTela = this.getContentPane();
// return containerTela;
// }
private void initTela(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 580));
setResizable(false);
setLocation(490, 140);
}
public void setPainelInicial(){
this.setTitle("Início");
this.setContentPane(pnlIni);
}
public void setPainelCadastro(){
this.setTitle("Cadastro");
this.setContentPane(pnlCad);
}
public void setPainelDados(){
this.setTitle("Página de "); //TODO pegar nome do user logado
this.setContentPane(pnlDados);
}
}
Handler:
package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class ButtonHandler implements ActionListener {
private Tela tela;
private JButton btCad;
private PainelCadastro pnlCad;
public ButtonHandler(JButton btCad) {
this.btCad = btCad;
this.tela = new Tela();
tela.setContentPane(pnlCad);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btCad){
tela.setContentPane(pnlCad);
tela.pack();
tela.setVisible(true);
}
}
}