日期:2014-05-20  浏览次数:20707 次

新手求解~
以下代码是在一个Frame窗口添加两个面板的:
1. 如果不添加最后两个add(),则只能显示contentPane2的内容,这是为什么?
2. 如果添加了最后两个add(),则会报错:Exception in thread "main" java.lang.IllegalArgumentException: adding container's parent to itself。 这是为什么?
3. 如果只加add(contentPane),则是整个窗口被contentPane2填满,然后在其上一块区域是contentPane,这是为什么?

已经知道可以将创建面板的部分代码移出Frame外再add的方式,只是对上面三个问题有疑惑,而且都是可以编译通过,但无法执行,我想语法应该没错,盼望高手解答,谢谢了~

代码:
import javax.swing.*;
import java.awt.*;
public class Ex1
{
  public static void main(String []args)
  {
    FrameDemo MyFrame=new FrameDemo();
    MyFrame.setVisible(true);
   }
}
class FrameDemo extends JFrame                  
{
  FrameDemo()
  {
    setSize(250,200);
    setBounds(500,500,500,500);  
     
     JPanel contentPane=new JPanel();
    setContentPane(contentPane);
    contentPane.setBackground(Color.white);
    contentPane.setLayout(new FlowLayout());

    JButton MyButton=new JButton("我是按钮");
    contentPane.add(MyButton);

    JLabel MyLabel=new JLabel("标签,我是按钮1");
    MyLabel.setForeground(Color.black);    
    contentPane.add(MyLabel);

    JPanel contentPane2=new JPanel();
    setContentPane(contentPane2);
    contentPane2.setBackground(Color.BLUE);
    contentPane2.setLayout(new FlowLayout());

    JButton MyButton2=new JButton("我是按钮2");
    contentPane2.add(MyButton2);

    JLabel MyLabel2=new JLabel("标签,我是按钮2");
    MyLabel2.setForeground(Color.black);    
    contentPane2.add(MyLabel2);
   
    add(contentPane);add(contentPane2);      //这就是最后两个add()方法
   }      
}

------解决方案--------------------
覆盖是由于  布局的问题, 你可以看看布局的东西 ,我也不是很熟悉,你可以把这个setContentPane();
方法屏蔽了在add看看还报错不, 

------解决方案--------------------

JPanel contentPane2=new JPanel();
    setContentPane(contentPane2);
    contentPane2.setBackground(Color.BLUE);
    contentPane2.setLayout(new FlowLayout());
//以上去掉,下面的contentPane2改为contentPane
    JButton MyButton2=new JButton("我是按钮2");
    contentPane2.add(MyButton2);

    JLabel MyLabel2=new JLabel("标签,我是按钮2");
    MyLabel2.setForeground(Color.black);    
    contentPane2.add(MyLabel2);
   
    add(contentPane);
add(contentPane2);  //去掉