在 JFrame 内切换 JPanel
问题:
我是 Java 组件新手,遇到了问题在 JFrame 内切换 JPanel。当我调用 gameOn() 时,框架表面变为空白,而不显示游戏面板。我该如何解决这个问题?
答案:
建议使用 CardLayout,而不是添加和删除组件。具体方法如下:
创建 CardLayout 对象和使用它的 JPanel:
<code class="java">CardLayout cardLayout = new CardLayout(); JPanel mainPanel = new JPanel(cardLayout);</code>
将菜单和游戏面板添加到 mainPanel:
<code class="java">MenuPanel menu = new MenuPanel(); GamePanel game = new GamePanel(); mainPanel.add(menu, "menu"); mainPanel.add(game, "game");</code>
在 gameOn() 方法中,只需使用 cardLayout 显示游戏面板,无需添加或删除任何组件:
<code class="java">public void gameOn() { cardLayout.show(mainPanel, "game"); }</code>
示例:
<code class="java">import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; class GameFrame extends JFrame implements ActionListener { public static void main(String[] args) { SwingUtilities.invokeLater(() -> new GameFrame().setVisible(true)); } private CardLayout cardLayout; private JPanel mainPanel; private MenuPanel menuPanel; private GamePanel gamePanel; public GameFrame() { cardLayout = new CardLayout(); mainPanel = new JPanel(cardLayout); menuPanel = new MenuPanel(); mainPanel.add(menuPanel, "menu"); gamePanel = new GamePanel(); mainPanel.add(gamePanel, "game"); JButton goGameButton = new JButton("Go to Game"); goGameButton.addActionListener(this); add(mainPanel); add(goGameButton, BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { cardLayout.show(mainPanel, "game"); } } class MenuPanel extends JPanel { public MenuPanel() { setBackground(Color.GREEN); add(new JLabel("Menu")); } @Override public Dimension getPreferredSize() { return new Dimension(300, 300); } } class GamePanel extends JPanel { public GamePanel() { setBackground(Color.BLUE); add(new JLabel("Game")); } @Override public Dimension getPreferredSize() { return new Dimension(300, 300); } }</code>
以上是如何使用 CardLayout 在 JFrame 中切换 JPanel?的详细内容。更多信息请关注PHP中文网其他相关文章!