在Java中使用CardLayout(Using CardLayout in Java)

2019-07-29 15:03发布

目前,我想要做一个游戏的菜单。 菜单看起来是这样的。 http://puu.sh/xGoC

理想的情况是,当我按下一个按钮,它会带我去游戏。 游戏看起来是这样的。 http://puu.sh/xGoV

我目前初始化一个JFrame()在我的主类,运行或者是菜单类或游戏类(两者均为JPanels)。

我怎么会去使用CardLayout让它这样我可以初始化游戏菜单,当我点击一个按钮,改变面板的游戏面板?

Answer 1:

我有一些示例代码对你来说,它并不完美,但它应该工作。 基本上,你要使用的布局管理器的一个或上一个电话。

由于这里只有两个小组,我只是通过他们使用周期的下一个电话。 这也可能是最好的,如果你虽然读的Swing文档,这个工作,但你可能有其他的要求也是如此。

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
}


Answer 2:

不要使用CardLayout了点。

相反,请从框架的内容窗格中的菜单面板,然后添加游戏盘。
记住要validate()的帧,以及。 事情是这样的:

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

在我目前的工作对我的程序有一个名为ViewManager类创建每个视图的静态实例,并将它们添加到一个数组对应于常量字段指数。 我也有场跟踪的面包屑/先前的观点回去。 这可能是重新发明轮子的情况下,但它可以让你控制它的一切。 而且它的效率。



文章来源: Using CardLayout in Java