Chamar JPanel por um Jbutton

Eu gostaria de chamar um formulário que criei em um JPanel a partir do clique de um botão.

Eu já li diversos fóruns enão consegui fazer com que o botão executa-se a ação.

Segue o meu código:

Método Principal

import javax.swing.JOptionPane;



public class principal extends javax.swing.JFrame {


    public principal() {
      
        initComponents();
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        cadastrar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        cadastrar.setText("Cadastrar");
        cadastrar.setFocusable(false);
        cadastrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cadastrar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastrarActionPerformed(evt);
            }
        });
        cadastrar.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                cadastrarAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jButton2.setText("Excluir");

        jButton3.setText("Visualizar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Relatorio");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                    .addComponent(cadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addGap(38, 38, 38))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(28, 28, 28)
                        .addComponent(jButton4))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cadastrar)
                        .addGap(28, 28, 28)
                        .addComponent(jButton2)))
                .addContainerGap(45, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

}                                        

private void cadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                          


}                                         

private void cadastrarAncestorAdded(javax.swing.event.AncestorEvent evt) {
// TODO add your handling code here:
}

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    public javax.swing.JButton cadastrar;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JFrame jFrame1;
    // End of variables declaration

}

Formulário de Cadastro

import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;

public class Cadastro extends javax.swing.JPanel {

    /** Creates new form Cadastro */
    public  Cadastro() {
        initComponents();
        
    }

    Cadastro(principal aThis, boolean b) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        codcd = new javax.swing.JTextField();
        titulo = new javax.swing.JTextField();
        autor = new javax.swing.JTextField();
        genero = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        ano = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        faixas = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        tempo = new javax.swing.JTextField();
        gravar = new javax.swing.JButton();

        jLabel1.setText("Código do CD");

        jLabel2.setText("Titulo");

        jLabel3.setText("Autor");

        jLabel4.setText("Genêro");

        codcd.setText("CodCd");
        codcd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codcdActionPerformed(evt);
            }
        });

        titulo.setText("titulo");
        titulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tituloActionPerformed(evt);
            }
        });

        autor.setText("autor");

        genero.setText("genero");

        jLabel5.setText("Ano");

        ano.setText("Ano");
        ano.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anoActionPerformed(evt);
            }
        });

        jLabel6.setText("Quantidade de Faixas");

        faixas.setText("faixas");

        jLabel7.setText("Tempo Total");

        tempo.setText("tempo");

        gravar.setText("Gravar");
        gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gravarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(autor, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(codcd, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel5)
                                    .addComponent(ano, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 87, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel2)
                                    .addComponent(faixas, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(titulo, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                                    .addComponent(genero))
                                .addGap(26, 26, 26))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(122, 122, 122)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(tempo, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(gravar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(jLabel7)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codcd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(titulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(autor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(genero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(faixas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tempo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(gravar)
                .addContainerGap(21, Short.MAX_VALUE))
        );
    }// </editor-fold>

private void codcdActionPerformed(java.awt.event.ActionEvent evt) {                                      

    int codCd;
        	while (true){
        		ActionEvent cod=evt;
        		if (cod==null){
        			int opcao;
                	Object[] botoes = {"Sim","Nao"};
                	opcao=JOptionPane.showOptionDialog(null," Voce ira perder seus dados.\n Tem Certeza que deseja sair?",
                	"Fechar",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null,botoes,botoes[0]);
                	if (opcao==JOptionPane.YES_OPTION){
                	return;}else{continue;}
                           
                	}
                        
        		codCd = -1;
        		
                        try {
//        			codCd = Integer.parseInt(codCd);
        			break;
        		} catch (NumberFormatException e) {
        			JOptionPane.showMessageDialog(null,"              Por favor\n" +
        				"Digite um n�mero inteiro.","Mensagem de erro",JOptionPane.ERROR_MESSAGE,null);
        		  }
        		
                }
    
    
    
    
}                                     

private void anoActionPerformed(java.awt.event.ActionEvent evt) {                                    
// TODO add your handling code here:
}                                   

private void tituloActionPerformed(java.awt.event.ActionEvent evt) {                                       
// TODO add your handling code here:
}                                      

private void gravarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}


    // Variables declaration - do not modify
    private javax.swing.JTextField ano;
    private javax.swing.JTextField autor;
    public javax.swing.JTextField codcd;
    private javax.swing.JTextField faixas;
    private javax.swing.JTextField genero;
    private javax.swing.JButton gravar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField tempo;
    private javax.swing.JTextField titulo;
    // End of variables declaration

}

Será que alguem consegue me ajudar.

Desde já muito obrigado.

Acho que isso seria feito de forma mais fácil se você construísse a GUI na mão…
Porém como não sou bom nisso, não posso ajudar…

Aprenda a fazer a GUI na mão que é melhor para você…
E faça antes que vicie no netbeans (como eu)
:frowning:

[quote=d34d_d3v1l]Acho que isso seria feito de forma mais fácil se você construísse a GUI na mão…
Porém como não sou bom nisso, não posso ajudar…

Aprenda a fazer a GUI na mão que é melhor para você…
E faça antes que vicie no netbeans (como eu)
:([/quote]

A um tempo atrás eu já fiz o label na mão só que isso não é nada prático, se existe como fazer de uma forma prática e mais rápida pq não o fazer.

Eu não posso toda vez que encontrar um dificuldade dar a volta por ela e sim passar por cima.

vc encontrará problemas mais adiante, assim como eu encontrei…

mas boa sorte =]

Dê dois cliques no botão que irá abrir o form de cadastro e no, seu método actionPerformed, faça:

new Cadastro().setVisible(true);

[quote=ViniGodoy]Dê dois cliques no botão que irá abrir o form de cadastro e no, seu método actionPerformed, faça:

new Cadastro().setVisible(true);

Acredito que ele quer fazer isso com um Painel… e não com um Frame…
Se eu nao tiver entendido errado…

Se isso resolveu o problema,
então desculpem o comentário idiota que eu fiz.

Se quiser só fazer paineis aparecerem, procure sobre o cardlayout ou sobre o JTabbedPane.

Galera muito obrigado pela ajuda o erro que eu estava cometendo era um JPanel no lugar de um JFrame.

Muito Obrigado d34d_d3v1l e ViniGodoy pela ajuda.

Mod pode fechar o tópico.

[]s

Cara, é melhor você criar código na mão como disse o amigo anteriormente, pois fica bem mais limpo o código.