0

Bonjour, i'm actually trying to switch from a jPanel to another one in my jFrame. i have change my code and here is what it look like i have followed this :

How to use CardLayout with Netbeans GUI Builder

my main :

 package testjframe;
public class TestJframe {
public static void main(String[] args) {
    new MyFrame().setVisible(true);
}

}

and my jFrame:

 package testjframe;
import java.awt.CardLayout;
public class MyFrame extends javax.swing.JFrame {

public MyFrame() {
    initComponents();

}

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

    mainPanel = new javax.swing.JPanel();
    panel2 = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    panel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    panel3 = new javax.swing.JPanel();
    jLabel3 = new javax.swing.JLabel();
    btn1 = new javax.swing.JButton();
    btn2 = new javax.swing.JButton();
    btn3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

    jLabel2.setText("jLabel2");

    javax.swing.GroupLayout panel2Layout = new javax.swing.GroupLayout(panel2);
    panel2.setLayout(panel2Layout);
    panel2Layout.setHorizontalGroup(
        panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 792, Short.MAX_VALUE)
        .addGroup(panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(0, 0, Short.MAX_VALUE)))
    );
    panel2Layout.setVerticalGroup(
        panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 460, Short.MAX_VALUE)
        .addGroup(panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(0, 0, Short.MAX_VALUE)))
    );

    mainPanel.add(panel2, "card3");

    jLabel1.setText("jLabel1");

    javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
    panel1.setLayout(panel1Layout);
    panel1Layout.setHorizontalGroup(
        panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 792, Short.MAX_VALUE)
        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE)))
    );
    panel1Layout.setVerticalGroup(
        panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 460, Short.MAX_VALUE)
        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE)))
    );

    mainPanel.add(panel1, "card2");

    jLabel3.setText("jLabel3");

    javax.swing.GroupLayout panel3Layout = new javax.swing.GroupLayout(panel3);
    panel3.setLayout(panel3Layout);
    panel3Layout.setHorizontalGroup(
        panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 792, Short.MAX_VALUE)
        .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(0, 0, Short.MAX_VALUE)))
    );
    panel3Layout.setVerticalGroup(
        panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 460, Short.MAX_VALUE)
        .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(0, 0, Short.MAX_VALUE)))
    );

    mainPanel.add(panel3, "card4");

    btn1.setText("1");
    btn1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btn1ActionPerformed(evt);
        }
    });

    btn2.setText("2");
    btn2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btn2ActionPerformed(evt);
        }
    });

    btn3.setText("3");
    btn3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btn3ActionPerformed(evt);
        }
    });

    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(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(btn1)
                    .addGap(261, 261, 261)
                    .addComponent(btn2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn3)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btn1)
                .addComponent(btn3)
                .addComponent(btn2))
            .addContainerGap())
    );

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

private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    CardLayout card = (CardLayout)mainPanel.getLayout();
    card.show(mainPanel, "panel1");
    System.out.println("1");
}                                    

private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    CardLayout card = (CardLayout) mainPanel.getLayout();
    card.show(mainPanel, "panel2");
    System.out.println("2");
}                                    

private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    CardLayout card = (CardLayout)mainPanel.getLayout();
    card.show(mainPanel, "panel3");
    System.out.println("3");
}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
    */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel mainPanel;
private javax.swing.JPanel panel1;
private javax.swing.JPanel panel2;
private javax.swing.JPanel panel3;
// End of variables declaration                   

}

but it didn't work, what i am missing or doing wrong ?

Romain
  • 19
  • 6
  • Could you add your code for the panel classes? Also can you confirm that the `btn1ActionPerformed` method is being called? If you could add any other code such as adding the button listener it would help a lot. – Michael Jul 30 '18 at 14:45
  • @Michael the btn1ActionPerformed work, i have add the code of the jPanel class – Romain Jul 30 '18 at 14:50
  • What happens when you run your code? How do the results differ from what you want? Take a moment to read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for tips about how to debug your code. – Code-Apprentice Jul 30 '18 at 14:50
  • Do you have code for `panelD`? – Michael Jul 30 '18 at 14:53
  • @Code-Apprentice my jFrame appear, i have apply a System.out.print("test"; to the button, when clic, "test" was shown inside the consol but my jPanel didn't change – Romain Jul 30 '18 at 14:53
  • @Michael it's the same as the panel1, he only difference is the text of the jLabel inside it – Romain Jul 30 '18 at 14:55
  • Did my solution fix this? – Michael Jul 30 '18 at 16:28
  • @Romain If the only difference is the text in the JLabel, then you should change the text of the JLabel. Remember the simplest solution is often the best solution. – Code-Apprentice Jul 30 '18 at 18:14
  • @Code-Apprentice jLabel is for test, to see that jPanel switch correctly – Romain Jul 30 '18 at 18:51
  • @Romain So in the final application, the two panels will be very different? Is that right? – Code-Apprentice Jul 30 '18 at 19:09
  • @Code-Apprentice yes, i'm learning java, i try different thing – Romain Jul 30 '18 at 19:42
  • We have no idea what layout manager your "monPanel" is using. But if it is using a GroupLayout like the "panel1" class then your code is missing all the constraints necessary to add components to a panel using the GroupLayout. – camickr Jul 30 '18 at 20:41

1 Answers1

0

Currently you're repainting the panel and then re-validating. This means you repaint it to look the same and then remove and add the components. You need to repaint after restructuring the components.

Try this:

monPanel.removeAll();
monPanel.add(new panel1());
monPanel.revalidate();
monPanel.repaint();
Michael
  • 3,411
  • 4
  • 25
  • 56
  • i have changed my code if you can have a look please – Romain Jul 31 '18 at 09:21
  • Is it a good idea to start simple? Create a JFrame and add a JPanel with a label and a button. When the button is pressed make it change to another panel containing a different label. If you get this working you should be able to find out the problem. – Michael Jul 31 '18 at 09:37
  • Also I recommend a few changes to your current code to tidy it up. Class names should be in upper camel case. Variables should generally be declared at the top. A lot of your variables can also be initialized when they are declared. Lastly you can use imports instead of qualified class names. – Michael Jul 31 '18 at 09:41
  • its what i'm actually trying to do, 1 jFrame with 1 jPanel, and inside that panel 3 jPanel i'll try to show with 3 button (one for each panel) – Romain Jul 31 '18 at 09:42
  • At the moment your code is quite long. For us to help it is good to have a small example we can easily run and test. – Michael Jul 31 '18 at 10:02