How to Change java Cardlayout from another separate class

蓝咒 提交于 2019-11-26 18:36:36

问题


Please I have been trying to switch CardLayout from another class (JPanel) which is one of the card on the CardLayout, I have search and made research about this for a very long time but found nothing helpful.

I have a CardLayout and two separate JPanels that I added to the CardLayout, now I want to be able to switch the cards after performing activities on the separate JPanel or separate class, so how do I switch the CardLayout from another class? my code below.

package myApp;
import java.awt.CardLayout;

public class TestmyCard extends javax.swing.JFrame {

/**
 * Creates new form TestmyCard
 */
public TestmyCard() {
    initComponents();
    jPanel1.add(new FirstCard(),"card3");
    jPanel1.add(new SecondCard(),"card4");
}

public void chgCard(String nwCard){
            CardLayout cl = (CardLayout)(jPanel1.getLayout());
   cl.show(jPanel1,nwCard);

}

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

    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jPanel3 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setName("Cards");
    jPanel1.setLayout(new java.awt.CardLayout());

    jPanel2.setName("card2");

    jLabel1.setText("second panel");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(119, 119, 119)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(203, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(140, 140, 140)
            .addComponent(jLabel1)
            .addContainerGap(92, Short.MAX_VALUE))
    );

    jPanel1.add(jPanel2, "card2");

    jPanel3.setBackground(new java.awt.Color(153, 255, 153));

    jButton1.setLabel("First Btn");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setLabel("Second Btn");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jButton1)
            .addGap(18, 18, 18)
            .addComponent(jButton2)
            .addContainerGap(181, Short.MAX_VALUE))
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
            .addContainerGap(27, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2))
            .addGap(20, 20, 20))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
        .addGroup(layout.createSequentialGroup()
            .addGap(37, 37, 37)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

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

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)    {                                         
    // TODO add your handling code here:
    CardLayout cl = (CardLayout)(jPanel1.getLayout());
   cl.show(jPanel1,"card3");
   //cl.next(jPanel1) ;
}                                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    CardLayout cl = (CardLayout)(jPanel1.getLayout());
   cl.show(jPanel1,"card4");
}                                        

/**
 * @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(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new TestmyCard().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration                   
}

FirstCard (separate jpanel)

package myApp;

public class FirstCard extends javax.swing.JPanel {

/**
 * Creates new form FirstCard
 */
public FirstCard() {
    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();
    guName = new javax.swing.JTextField();
    guAddrs = new javax.swing.JTextField();
    jLabel14 = new javax.swing.JLabel();
    jLabel15 = new javax.swing.JLabel();
    guOccu = new javax.swing.JTextField();
    jLabel16 = new javax.swing.JLabel();
    guPhone = new javax.swing.JTextField();

    jLabel1.setText("Guarantee Name :");

    jLabel14.setText("Address :");

    jLabel15.setText("Occupation :");

    jLabel16.setText("Phone :");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel14)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(guAddrs, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel16)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(guPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel15)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(guOccu, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(guName, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(228, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(43, 43, 43)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(guName, 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(jLabel15)
                .addComponent(guOccu, 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(jLabel14)
                .addComponent(guAddrs, 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(jLabel16)
                .addComponent(guPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(135, Short.MAX_VALUE))
    );
}// </editor-fold>                        
// Variables declaration - do not modify                     
private javax.swing.JTextField guAddrs;
private javax.swing.JTextField guName;
private javax.swing.JTextField guOccu;
private javax.swing.JTextField guPhone;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
// End of variables declaration                   
}

SecondCard (separate jpanel)

package myApp;

public class SecondCard extends javax.swing.JPanel {

/**
 * Creates new form SecondCard
 */
public SecondCard() {
    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();
    jButton1 = new javax.swing.JButton();

    jLabel1.setText("this is the second card");

    jButton1.setText("SwitchCard");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(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()
            .addGap(120, 120, 120)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(jLabel1))
            .addContainerGap(173, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(62, 62, 62)
            .addComponent(jLabel1)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addContainerGap(183, Short.MAX_VALUE))
    );
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    TestmyCard nc = new TestmyCard();
    nc.chgCard("Card2");
}

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

回答1:


In your provided code, you never added FirstCard and SecondCard, to the JPanel having layout set to CardLayout. Since what you writing is this :

jPanel1.add(jPanel2, "card2");

here jPanel2 is an instance of JPanel, as you have initialized this in your TestmyClass Class, as :

jPanel2 = new javax.swing.JPanel();

instead I guess what you should be writing is :

jPanel2 = new SecondCard(passPanelWithCardLayoutAsArgument); // So that you can manoeuvre around b/w other JPanels

Here is a small working example for your help :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutExample
{
    private JPanel contentPane;
    private MyPanel panel1;
    private MyPanel panel2;
    private MyPanel panel3;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Card Layout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new CardLayout());

        panel1 = new MyPanel(contentPane
                , Color.RED.darker().darker());
        panel2 = new MyPanel(contentPane
                , Color.GREEN.darker().darker());
        panel3 = new MyPanel(contentPane
                , Color.DARK_GRAY); 

        contentPane.add(panel1, "Panel 1"); 
        contentPane.add(panel2, "Panel 2");
        contentPane.add(panel3, "Panel 3");         

        frame.setContentPane(contentPane);      
        frame.pack();   
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new CardLayoutExample().displayGUI();
            }
        });
    }
}

class MyPanel extends JPanel 
{

    private JButton jcomp1;
    private JPanel contentPane;
    private Color backgroundColour;

    public MyPanel(JPanel panel, Color c) 
    {   
        contentPane = panel;
        backgroundColour = c;

        setOpaque(true);
        setBackground(backgroundColour);

        //construct components
        jcomp1 = new JButton ("Show New Panel");
        jcomp1.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                cardLayout.next(contentPane);
            }
        });

        add(jcomp1);
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(500, 500));
    }
}

LATEST EDIT : *Using your components and trying to put that into CardLayout, with this code : *

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutExample
{
    private JPanel contentPane;
    private FirstCard panel1;
    private SecondCard panel2;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Card Layout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new CardLayout());

        panel1 = new FirstCard(contentPane);
        panel2 = new SecondCard(contentPane);

        contentPane.add(panel1, "Panel 1"); 
        contentPane.add(panel2, "Panel 2");     

        frame.setContentPane(contentPane);      
        frame.pack();   
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new CardLayoutExample().displayGUI();
            }
        });
    }
}

class FirstCard extends javax.swing.JPanel 
{
    private javax.swing.JTextField addField;
    private javax.swing.JTextField nameField;
    private javax.swing.JTextField occField;
    private javax.swing.JTextField phoneField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JLabel addLabel;
    private javax.swing.JLabel occLabel;
    private javax.swing.JLabel phoneLabel;
    private JPanel centerPanel;
    private JPanel contentPane;
    private JButton nextButton;

    public FirstCard(JPanel cp) 
    {
        this.contentPane = cp;
        initComponents();
    }

    private void initComponents() 
    {
        setOpaque(true);
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        setBackground(Color.RED);
        setLayout(new BorderLayout(5, 5));

        nameLabel = new javax.swing.JLabel("Guarantee Name : ");
        nameField = new javax.swing.JTextField();   
        addLabel = new javax.swing.JLabel("Address : ");
        addField = new javax.swing.JTextField();        
        occLabel = new javax.swing.JLabel("Occupation : ");
        occField = new javax.swing.JTextField();
        phoneLabel = new javax.swing.JLabel("Phone : ");
        phoneField = new javax.swing.JTextField();
        centerPanel = new JPanel();
        nextButton = new JButton("Next");
        nextButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                nextButtonAction(ae);
            }
        });

        centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        centerPanel.setOpaque(true);
        centerPanel.setBackground(Color.WHITE);
        centerPanel.setLayout(new GridLayout(0, 2, 5, 5));
        centerPanel.add(nameLabel);
        centerPanel.add(nameField);
        centerPanel.add(addLabel);
        centerPanel.add(addField);
        centerPanel.add(occLabel);
        centerPanel.add(occField);
        centerPanel.add(phoneLabel);
        centerPanel.add(phoneField);

        add(centerPanel, BorderLayout.CENTER);
        add(nextButton, BorderLayout.PAGE_END);
    }                   

    private void nextButtonAction(ActionEvent ae)
    {
        CardLayout layout = (CardLayout)contentPane.getLayout();
        layout.next(contentPane);
    }
}

class SecondCard extends javax.swing.JPanel 
{

    private javax.swing.JButton nextButton;
    private javax.swing.JLabel textLabel;
    private JPanel contentPane;

    public SecondCard(JPanel cp) 
    {
        contentPane = cp;
        initComponents();
    }

    private void initComponents() 
    {

        setOpaque(true);
        setBackground(Color.GREEN.darker().darker());
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        textLabel = new JLabel("this is the second card", JLabel.CENTER);
        textLabel.setForeground(Color.WHITE);
        nextButton = new javax.swing.JButton();

        nextButton.setText("SwitchCard");
        nextButton.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent evt) 
            {
                jButton1ActionPerformed(evt);
            }
        });

        add(textLabel);
        add(nextButton);
    }

    private void jButton1ActionPerformed(ActionEvent evt) 
    {
        CardLayout layout = (CardLayout) contentPane.getLayout();
        layout.show(contentPane, "Panel 1");
    }
}

Method to clear fields

private void clearFields()
{
    Component components[] = centerPanel.getComponents();
    for (Component comp : components)
    {
        if (comp instanceof JTextField)
        {
            JTextField tfield = (JTextField) comp;
            tfield.setText("");
        }
        else if (comp instanceof JComboBox)
        {
            JComboBox cbox = (JComboBox) comp;
            cbox.setSelectedIndex(0);
        }
        else if (comp instanceof JRadioButton)
        {
            JRadioButton rbut = (JRadioButton) comp;
            rbut.setSelected(false);
        }
    }
}

And you will call this inside the actionPerformed() method of the Button, which will take you to the next Card.



来源:https://stackoverflow.com/questions/13377386/how-to-change-java-cardlayout-from-another-separate-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!