在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中文網其他相關文章!