CardLayout + JPanel [RESOLVIDO]

10 respostas
sk2ck

Estou com um pequeno problema.

Tenho um jframe com um jpanel principal. Acontece que fiz varios outros jpanel separadamente com o netbeans 6.8. Agora gostaria de carregar dinamicamente esses jpanel que montei separadamente dentro do jpanel principal do jframe. Para isso pretendo usar cardlayout. Consigo fazer isso quando tenho os jpanel dentro do meu jframe, mas não consigo carrega-los quando o tal jpanel esta fora, ou seja em um outro pacote dentro do mesmo projeto. Minha pergunta portanto é: como faço para carregar um jpanel com cardlayout em um jframe, sendo que tal jpanel esta feito separamente em outro pacote do projeto?

Não sei se consegui ser claro… mas se alguém souber será de grande ajuda.
Obrigado

10 Respostas

Eric_Yuzo

Do mesmo jeito que faria com um JPanel no mesmo pacote. Crie o objeto JPanel que você definiu e adicione ao painel principal com CardLayout.

sk2ck

não entendi direito mas vou tentar ser mais claro. Meu outro jpanel é externo… ou seja em outro arquivo .java que extende javax.swing.JPanel . Nessas condições não aparece a opção de colocar um nome de cartão para o layout desse jpanel externo. Portanto não consigo chama-lo a ocupar o jpPrincipal.

alguma idéia de como resolver isso?

Eric_Yuzo

Agora entendi. Sua dúvida não é em relação ao CardLayout em si, mas sim em relação ao editor do NetBeans, é isso?

Então clique com o botão direito na classe que estende JPanel, mande compilar e depois arraste-a para dentro do JFrame.

sk2ck

Sem mais delongas vamos aos codigos:

Essa é a classe com três jpanel.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Exemplo.java
 *
 * Created on 30/12/2011, 00:25:45
 */

package cardlayout;

import cardteste.jpexterno;
import java.awt.CardLayout;

/**
 *
 * @author sk2ck
 */
public class Exemplo extends javax.swing.JFrame {

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

    private void showTela(String nome)
    {
        CardLayout card = (CardLayout)jpprincipal.getLayout();
        card.show(jpprincipal, nome);
    }

    /** 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() {

        jTela1 = new javax.swing.JButton();
        jTela2 = new javax.swing.JButton();
        jTela3 = new javax.swing.JButton();
        jpprincipal = new javax.swing.JPanel();
        jptela1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jptela2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jptela3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTela1.setText("Tela1");
        jTela1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTela1ActionPerformed(evt);
            }
        });

        jTela2.setText("Tela2");
        jTela2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTela2ActionPerformed(evt);
            }
        });

        jTela3.setText("Tela3");
        jTela3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTela3ActionPerformed(evt);
            }
        });

        jpprincipal.setLayout(new java.awt.CardLayout());

        jLabel1.setText("jLabel1");

        jButton1.setText("jButton1");

        javax.swing.GroupLayout jptela1Layout = new javax.swing.GroupLayout(jptela1);
        jptela1.setLayout(jptela1Layout);
        jptela1Layout.setHorizontalGroup(
            jptela1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela1Layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addGroup(jptela1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1))
                .addContainerGap(328, Short.MAX_VALUE))
        );
        jptela1Layout.setVerticalGroup(
            jptela1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela1Layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(jLabel1)
                .addGap(30, 30, 30)
                .addComponent(jButton1)
                .addContainerGap(127, Short.MAX_VALUE))
        );

        jpprincipal.add(jptela1, "tela1");

        jLabel2.setText("jLabel2");

        jButton2.setText("jButton2");

        javax.swing.GroupLayout jptela2Layout = new javax.swing.GroupLayout(jptela2);
        jptela2.setLayout(jptela2Layout);
        jptela2Layout.setHorizontalGroup(
            jptela2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela2Layout.createSequentialGroup()
                .addGroup(jptela2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jptela2Layout.createSequentialGroup()
                        .addGap(192, 192, 192)
                        .addComponent(jLabel2))
                    .addGroup(jptela2Layout.createSequentialGroup()
                        .addGap(84, 84, 84)
                        .addComponent(jButton2)))
                .addContainerGap(285, Short.MAX_VALUE))
        );
        jptela2Layout.setVerticalGroup(
            jptela2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela2Layout.createSequentialGroup()
                .addGap(99, 99, 99)
                .addComponent(jLabel2)
                .addGap(45, 45, 45)
                .addComponent(jButton2)
                .addContainerGap(136, Short.MAX_VALUE))
        );

        jpprincipal.add(jptela2, "tela2");

        jLabel3.setText("jLabel3");

        jButton3.setText("jButton3");

        javax.swing.GroupLayout jptela3Layout = new javax.swing.GroupLayout(jptela3);
        jptela3.setLayout(jptela3Layout);
        jptela3Layout.setHorizontalGroup(
            jptela3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela3Layout.createSequentialGroup()
                .addGap(156, 156, 156)
                .addComponent(jLabel3)
                .addContainerGap(321, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jptela3Layout.createSequentialGroup()
                .addContainerGap(253, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addGap(181, 181, 181))
        );
        jptela3Layout.setVerticalGroup(
            jptela3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptela3Layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(jButton3)
                .addContainerGap(206, Short.MAX_VALUE))
        );

        jpprincipal.add(jptela3, "tela3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpprincipal, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTela1)
                        .addGap(18, 18, 18)
                        .addComponent(jTela2)
                        .addGap(18, 18, 18)
                        .addComponent(jTela3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTela1)
                    .addComponent(jTela2)
                    .addComponent(jTela3))
                .addGap(18, 18, 18)
                .addComponent(jpprincipal, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                .addContainerGap())
        );

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

    private void jTela1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        showTela("tela1");
    }                                      

    private void jTela3ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        showTela("tela3");
    }                                      

    private void jTela2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        showTela("tela2");
    }                                      

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jTela1;
    private javax.swing.JButton jTela2;
    private javax.swing.JButton jTela3;
    private javax.swing.JPanel jpprincipal;
    private javax.swing.JPanel jptela1;
    private javax.swing.JPanel jptela2;
    private javax.swing.JPanel jptela3;
    // End of variables declaration                   

}

e quero carregar esse jpexterno apresentado logo abaixo dentro do jptela1 da classe acima.

codigo jpexterno:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jpexterno.java
 *
 * Created on 30/12/2011, 11:15:54
 */

package cardteste;

/**
 *
 * @author sk2ck
 */
public class jpexterno extends javax.swing.JPanel {

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

    /** 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();

        jLabel1.setText("JPExterno");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(203, 203, 203)
                .addComponent(jLabel1)
                .addContainerGap(307, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(186, 186, 186)
                .addComponent(jLabel1)
                .addContainerGap(213, Short.MAX_VALUE))
        );
    }// </editor-fold>


    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    // End of variables declaration

}

note que na primeira classe Exemplo, uso cardlayout para carregar entre os jpanel dessa classe… mas para um jpanel de uma classe externa como a classe jpexterna do codigo acima, não estou conseguindo. Gostaria que quando clicasse no botão tela1, carregasse o jpanel jpexterno.

deu pra entender agora… ou ainda esta confuso?

Eric_Yuzo

Sim, mas você quer fazer isso via código ou via editor gráfico do NetBeans?

Marlon_Meneses

se é que eu entendi…

na sua classse JFrame, no mode desing clique com o botao direito no panel que você adicionou e depois selecione “Personalizar código”
em seguida modifique o construtor do panel selecionada para o seu panel externo!

entendeu?

sk2ck

Eric gostaria de fazer isso via código… vc sabe como é esse codigo?

Eric_Yuzo

Basicamente tem que adicionar o painel ao container passando um nome. Este nome deve ser único entre os cards, pois é por ele que o seu painel é acessado. Exemplo:

SeuPanel pnlExterno = new SeuPanel(); cardPane.add(pnlExterno, "painel externo"); // cardPane deve ser o painel com CardLayout, que seria o jpPrincipal no seu caso
Depois você acessa este painel com método show de CardLayout:

((CardLayout) cardPane.getLayout()).show(cardPane, "painel externo"); // para exibir pnlExterno

A princípio é isto. Se quiser mais detalhes pode dar uma olhada aqui: http://devsv.wordpress.com/2011/04/23/layout-manager-vi-card/
Também tem um exemplo aqui: http://www.guj.com.br/java/225883-duvidacard-layout#1158302

E caso surjam mais dúvidas, torne a postar.

sk2ck

Eric muito obrigado pelas suas contribuições… deu certo e com os links que passou entendi melhor como funciona. Desculpa-me fazer-lhe responder perguntas de um iniciante no dia 30, mas vc salvou minha vida hoje. Muito obrigado… tenha um 2012 cheio de felicidades!

Eric_Yuzo

Haha, relaxa cara. Aqui ninguém responde por obrigação e sim por vontade própria.

Valeu e também desejo um ano novo repleto de saúde, paz e realizações a você e a toda comunidade!

[ ]'s

Criado 29 de dezembro de 2011
Ultima resposta 30 de dez. de 2011
Respostas 10
Participantes 3