在JFrame 內切換JPanel
問題:
問題:問題:
CardLayout cardLayout = new CardLayout(); JPanel mainPanel = new JPanel(cardLayout);
mainPanel.add(menuPanel, "menu"); mainPanel.add(gamePanel, "game");建立一個CardLayout 物件並將其指派給JPanel 作為其佈局管理器:
cardLayout.show(mainPanel, "game");將所需的面板加入到主面板,用唯一的名稱標識每個面板:
輕鬆切換面板,無需複雜的添加/刪除操作。
簡化程式碼建置並降低執行階段錯誤的風險。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; public class GameFrame extends JFrame { CardLayout cardLayout; // CardLayout for managing panels JPanel mainPanel; // Main panel to hold the different JPanels public GameFrame() { cardLayout = new CardLayout(); mainPanel = new JPanel(cardLayout); MenuPanel menuPanel = new MenuPanel(); // Menu panel GamePanel gamePanel = new GamePanel(); // Game panel mainPanel.add(menuPanel, "menu"); // Add menu panel with "menu" identifier mainPanel.add(gamePanel, "game"); // Add game panel with "game" identifier JButton startGameButton = new JButton("Start Game"); startGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cardLayout.show(mainPanel, "game"); // Show game panel when button is clicked } }); add(mainPanel); // Add main panel to the JFrame add(startGameButton, BorderLayout.SOUTH); // Add the start game button below the main panel setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(new Dimension(600, 400)); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new GameFrame()); } class MenuPanel extends JPanel { // Menu panel with menu text MenuPanel() { setBackground(Color.GREEN); add(new JLabel("Menu")); } } class GamePanel extends JPanel { // Game panel with game text GamePanel() { setBackground(Color.BLUE); add(new JLabel("Game")); } } }在單一容器中有效管理多個面板。 程式碼範例:
以上是如何使用 CardLayout 在 JFrame 中的 JPanel 之間高效切換?的詳細內容。更多資訊請關注PHP中文網其他相關文章!