编程语言
首页 > 编程语言> > 如何从另一个单独的类更改java Cardlayout

如何从另一个单独的类更改java Cardlayout

作者:互联网

请问我一直在尝试从另一个类(JPanel)切换CardLayout,这是CardLayout上的卡之一,我已经搜索并对此进行了很长时间的研究,但没有发现任何有用的信息.

我有一个CardLayout和两个单独的JPanels,我添加到CardLayout,现在我希望能够在单独的JPanel或单独的类上执行活动后切换卡,那么如何从另一个类切换CardLayout?我的代码如下.

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(单独的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(单独的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
}

解决方法:

在您提供的代码中,您从未将FirstCard和SecondCard添加到布局设置为CardLayout的JPanel中.你写的是这样的:

jPanel1.add(jPanel2, "card2");

这里jPanel2是JPanel的一个实例,因为你已经在TestmyClass类中初始化了它,如下所示:

jPanel2 = new javax.swing.JPanel();

相反,我想你应该写的是:

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

以下是一个小工作示例供您使用:

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));
    }
}

最新编辑:
*使用您的组件并尝试将其放入CardLayout,使用以下代码:*

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");
    }
}

清除字段的方法

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);
        }
    }
}

你将在Button的actionPerformed()方法中调用它,它将带你到下一张Card.

标签:cardlayout,java,swing,jpanel
来源: https://codeday.me/bug/20190926/1820125.html