如何在JFrame中切换JPanel

如果您对我的信息不够,请原谅我!

考虑下面的代码。 添加框架中显示的菜单和菜单,没有问题。 我想当gameOn()被调用来删除菜单,而是开始游戏。 下面的代码只是使框架表面“空白”,没有添加游戏面板。

任何想法/build议如何解决? MenuPanel有一个mouselistener。

public class GameFrame extends JFrame { private MenuPanel mp; //extends JPanel private GamePanel gp; //extends JPanel public GameFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(new Dimension(GameFrame.XSIZE, GameFrame.YSIZE)); setLocationRelativeTo(null); setVisible(true); mp = new MenuPanel(this); add(mp); } public void gameOn() { remove(mp); GamePanel gp = new GamePanel(5); add(gp); } } 

不要尝试添加删除组件,请使用CardLayout

 CardLayout cardLayout = new CardLayout(); JPanel mainPanel = new JPanel(cardLayout); MenuPanel menu = new MenuPanel(); GamePanel game = new GamePanel(); mainPanel.add(menu, "menu"); mainPanel.add(game, "game"); ... public void gameOn() { cardLayout.show(mainPanel, "game"); } 

gameOn()被调用时, menu将被推回到后面,并将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 implements ActionListener{ CardLayout cardLayout; JPanel mainPanel; MenuPanel menu; GamePanel game; public GameFrame() { cardLayout = new CardLayout(); mainPanel = new JPanel(cardLayout); menu = new MenuPanel(); game = new GamePanel(); mainPanel.add(menu, "menu"); mainPanel.add(game, "game"); JButton goGame = new JButton("Go TO Game"); goGame.addActionListener(this); add(mainPanel); add(goGame, BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationByPlatform(true); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { gameOn(); } public void gameOn() { cardLayout.show(mainPanel, "game"); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { GameFrame gameFrame = new GameFrame(); } }); } } 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); } } 

在添加GamePanel之后,执行validate();

 public void gameOn() { remove(mp); gp = new GamePanel(5); add(gp); validate(); 

}

删除一个面板并添加另一个面板后,需要repaint()setVisible(true)应该在将组件添加到框架后完成,并且我build议在EDT线程上执行像UI这样的重大更改以避免干扰。