2012-11-06 113 views
0

我有以下代码,但我的JPanel只是不显示。我无法弄清楚为什么。你明白为什么?我看到的是黑色背景中的JFrame我不能将jpanel添加到jframe

public class ShapeFrame extends JFrame 
{ 
    private JPanel outlinePanel; 

    public ShapeFrame(LinkedList<Coordinate> list) 
    { 
     super("Outline/Abstract Image"); 
     setSize(950, 500); 
     setLayout(null); 
     setBackground(Color.BLACK); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel outlinePanel = new JPanel(); 
     outlinePanel.setBackground(Color.WHITE); 
     outlinePanel.setBorder(null); 
     outlinePanel.setBounds(50, 50, 400, 400); 
     add(outlinePanel); 


//  abstractPanel = new JPanel(); 
//  abstractPanel.setBackground(Color.WHITE); 
//  abstractPanel.setBounds(500, 50, 400, 400); 
//  add(abstractPanel); 
    } 
+5

不要使用空白布局 – MadProgrammer

+3

我同意@MadProgrammer,你应该避免空布局,但你当前的代码不显示错误。如果你显示这个JFrame,JPanel将被添加并且会被看到。我看到的唯一的其他错误是ShapeFrame构造函数局部的outlinePanel变量会隐藏otulinePanel类字段,该字段当然为空。也许这就是你错误和困惑的根源。 –

+2

当我运行你在这里发布的代码时,我得到一个灰色背景和一个白色方块的窗口(我认为这是你的'outlinePanel'。请发布一个[SSCCE](http://www.sscce.org) ),它重现了你所问的确切问题。 –

回答

3

我得到的是与它的白色方形框架...

您应该使用getContentPane().setBackground()设置帧的回地面

框架由层组成。通常,您看到的内容(大多数情况下会自动添加)添加到覆盖框架的内容窗格。

enter image description here

(图片来自Java步道借)

所以设置框的背景 “似乎” 没有任何效果。

使用你的代码...

enter image description here

使用getContent().setBackground(...)

enter image description here

这是我使用来测试你的代码的代码......

public class BadLayout01 { 

    public static void main(String[] args) { 
     new BadLayout01(); 
    } 

    public BadLayout01() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       ShapeFrame shapeFrame = new ShapeFrame(); 
       shapeFrame.setSize(525, 525); 
       shapeFrame.setVisible(true); 

      } 
     }); 
    } 

    public class ShapeFrame extends JFrame { 

     private JPanel outlinePanel; 

     public ShapeFrame() { 
      super("Outline/Abstract Image"); 
      setSize(950, 500); 
      setLayout(null); 
      getContentPane().setBackground(Color.BLACK); 
//   setBackground(Color.BLACK); 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      JPanel outlinePanel = new JPanel(); 
      outlinePanel.setBackground(Color.WHITE); 
      outlinePanel.setBorder(null); 
      outlinePanel.setBounds(50, 50, 400, 400); 
      add(outlinePanel); 


//  abstractPanel = new JPanel(); 
//  abstractPanel.setBackground(Color.WHITE); 
//  abstractPanel.setBounds(500, 50, 400, 400); 
//  add(abstractPanel); 
     } 
    } 
}