在JFrame中用JPanel替换JPanel

我有一个扩展JFrame的类,它有一个BorderLayout。 它有两个类型为JPanel的私有实例变量。 它们代表按钮面板,称为flipButton和confidenceButtons。 单击按钮时,按钮面板将被另一个按钮面板替换。 也就是说,如果单击flipButton中的按钮,则flipButton将替换为confidenceButton。 我试着这样做:

  私有类FlipListener实现ActionListener {public void actionPerformed(ActionEvent e){remove(flipButton); 添加(confidenceButtons,BorderLayout.SOUTH); validation(); 私有类ColorListener实现ActionListener {... public void actionPerformed(ActionEvent e){... remove(confidenceButtons); 添加(flipButton,BorderLayout.SOUTH); validation();  }} 

flipButton中的按钮具有FlipListeners,而ConfidentButton中的按钮具有ColorListeners。 程序运行时,单击按钮将删除面板,但不会添加任何内容来替换它。 我究竟做错了什么?

编辑

CardLayout原来是一个简单易行的解决方案。 事实certificate,上面的代码确实有效; 问题是我的代码的另一部分中的拼写错误。 >。但是,我总是在使用这些方法时遇到了麻烦,我发现CardLayout简化了它。 谢谢。

使用CardLayout ,如下所示。

游戏视图高分视图

revalidate()+ repaint()应该是技巧,例如这里

编辑:

觉得你有问题, 这里的例子和一遍又一遍垃圾桶的例子 ,随时再根据代码构建你的问题

另一种方式是看安德鲁汤普森添加的优秀例子:-) +1

尝试使用getContentPane()来调用remove(),add()方法等。:

getContentPane().remove(flipButton); getContentPane().add(confidenceButtons,BorderLayout.SOUTH); getContentPane().revalidate(); getContentPane().repaint(); 

编辑:这段代码对我来说很有用:

 import java.awt.BorderLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Frame extends JFrame { JPanel flipButton =new JPanel(); JPanel confidenceButtons =new JPanel(); public Frame() throws HeadlessException { super(); this.setLayout(new BorderLayout()); JButton b1=new JButton("flip"); b1.addActionListener(new FlipListener()); flipButton.add(b1); JButton b2=new JButton("color"); b2.addActionListener(new ColorListener()); confidenceButtons.add(b2); this.getContentPane().add(flipButton,BorderLayout.SOUTH); this.setSize(250,250); this.pack(); this.setVisible(true); } private class FlipListener implements ActionListener{ public void actionPerformed(ActionEvent e){ remove(flipButton); add(confidenceButtons,BorderLayout.SOUTH); validate(); repaint(); } } private class ColorListener implements ActionListener{ public void actionPerformed(ActionEvent e){ remove(confidenceButtons); add(flipButton,BorderLayout.SOUTH); validate(); repaint(); } } /** * @param args */ public static void main(String[] args) { new Frame(); } }