Using CardLayout in Java

2019-03-01 10:14发布

I'm currently trying to make a game with a menu. Menu looks like this. http://puu.sh/xGoC

Ideally, when I push a button, it will bring me to the game. The game looks like this. http://puu.sh/xGoV

I currently initialize a JFrame() in my main class which runs either the menu class or the game class (Both of which are JPanels).

How would I go about using CardLayout to make it so that I can initialize the game menu and when I click a button, change the panel to the game panel?

2条回答
戒情不戒烟
2楼-- · 2019-03-01 10:42

Don't use CardLayout for that.

Instead, remove the menu panel from the frame's content pane and add the game panel.
Remember to validate() the frame as well. Something like this:

public static final int VIEW_MENU = 0;
public static final int VIEW_GAME = 1;

private static Container content;
...
content = frame.getContentPane();

public static void setView(int view){
    if(view == VIEW_MENU){
        content.remove(menuPanel);
        content.add(gamePanel);
    } else {
        content.remove(gamePanel);
        content.add(menuPanel);
    }
    frame.validate();
}

In the program that I'm currently working on I have a class called ViewManager that creates static instances of each view and adds them to an array with indices that correspond to the constant fields. I also have fields to keep track of previous views for breadcrumbs / going back. It might be a case of re-inventing the wheel, but it allows you to control everything about it. And it's efficient.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-01 10:43

I've got some sample code for you, it's not perfect, but it should work. Basically, you want to use the NEXT or PREVIOUS calls on the layout manager.

As there's only two panels, I just use the NEXT call to cycle through them. It's probably the best if you read the Swing documentation though, this works, but you might have other requirements as well.

import java.awt.CardLayout;


public class CardLayoutUsage extends javax.swing.JFrame {

    public CardLayoutUsage() {
        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() {

        containerPanel = new javax.swing.JPanel();
        menuPanel = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        gamePanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

        jButton2.setText("Go to Game");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout menuPanelLayout = new javax.swing.GroupLayout(menuPanel);
        menuPanel.setLayout(menuPanelLayout);
        menuPanelLayout.setHorizontalGroup(
            menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
                .addContainerGap(135, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(149, 149, 149))
        );
        menuPanelLayout.setVerticalGroup(
            menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
                .addContainerGap(141, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(134, 134, 134))
        );

        containerPanel.add(menuPanel, "card2");

        gamePanel.setBackground(new java.awt.Color(255, 255, 204));

        jButton1.setText("Go to Menu");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
        gamePanel.setLayout(gamePanelLayout);
        gamePanelLayout.setHorizontalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
                .addContainerGap(138, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(147, 147, 147))
        );
        gamePanelLayout.setVerticalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
                .addContainerGap(152, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(123, 123, 123))
        );

        containerPanel.add(gamePanel, "card3");

        getContentPane().add(containerPanel, java.awt.BorderLayout.CENTER);

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        CardLayout cl = (CardLayout)(containerPanel.getLayout());
        cl.next(containerPanel);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        CardLayout cl = (CardLayout)(containerPanel.getLayout());
        cl.next(containerPanel);
    }

    /**
     * @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(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CardLayoutUsage.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 CardLayoutUsage().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel containerPanel;
    private javax.swing.JPanel gamePanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel menuPanel;
    // End of variables declaration
}
查看更多
登录 后发表回答