[英]Replacing JPanel with JPanel in a JFrame
我有一个扩展JFrame的类,并且它具有BorderLayout。 它具有两个JPanel类型的私有实例变量。 它们代表按钮面板,分别称为flipButton和confidenceButtons。 当您单击按钮时,按钮面板将被另一个按钮面板代替。 也就是说,如果单击flipButton中的按钮,则flipButton将替换为confidenceButtons。 我试图这样做:
private class FlipListener implements ActionListener{ public void actionPerformed(ActionEvent e){ remove(flipButton); add(confidenceButtons,BorderLayout.SOUTH); validate(); ... } } private class ColorListener implements ActionListener{ ... public void actionPerformed(ActionEvent e){ ... remove(confidenceButtons); add(flipButton,BorderLayout.SOUTH); validate(); } }
flipButton中的按钮具有FlipListeners,confidenceButtons中的按钮具有ColorListeners。 程序运行时,单击一个按钮将删除面板,但是没有添加任何内容来替换它。 我究竟做错了什么?
编辑
事实证明CardLayout是一个简单易用的解决方案。 事实证明,以上代码确实有效; 问题出在我代码的另一部分。 >。<但是,我在使用这些方法时总是遇到麻烦,我发现CardLayout为我简化了它。 谢谢。
使用CardLayout ,如图所示这里 。
尝试使用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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.