2011-09-01 116 views
2

我对JFrame和关键字“this”有问题。当我使用frame.getContentPane时,除非用“this”替换frame,否则组件不会显示。看起来getContentPane没有得到JFrame内容窗格,它有其他的东西,我不知道它是什么。恐怕我有两个不同的JFrame组件,即使我只声明了一个。有人可以解释这个问题吗?
这是我的代码:
组件在使用JFrame时不显示

public class Form1 extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 
    JFrame frame = new JFrame("TableLayout"); 
    Container content = frame.getContentPane();//this doesn't work unless I replace "frame" with the key word "this"/// 
public Form1()//constructor 
{ 
    String label[] = {"Top", "Bottom", "Add", "Delete", "Center", "Overlap"}; 
    double border = 5; 
    double size[][] = 
     {{border, 0.20, border, TableLayout.FILL, border, 0.80, border}, // Columns 
     {border, 0.15, border, TableLayout.FILL, border, 0.10, border}}; // Rows 
    JButton button[] = new JButton[label.length]; 
    for (int i = 0; i < label.length; i++) 
    { 
     button[i] = new JButton(label[i]); 
    } 
    content.add (button[0], "1, 1, 5, 1"); // Top (row,column) 
    content.add (button[1], " 1, 5, 5, 5"); // Bottom 
    content.add ((button[2], "1, 3  "); // Left 
    content.add (button[3],"5, 3,  "); // Right 
    this.pack(); 
    } 
} 
+0

可悲的是,我已经做了不止一次,而这重多-factoring。 :-) – trashgod

回答

4
public class Form1 extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 
    JFrame frame = new JFrame("TableLayout"); 

类是框架,也有一个名为frame一个Frame属性。当然有两个框架!

更改这个..

public class Form1 extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 
    JFrame frame = new JFrame("TableLayout"); 
    Container content = frame.getContentPane();//this doesn't work unless I replace "frame" with the key word "this"/// 
public Form1()//constructor 
{ 

要更多的东西一样(明确的答案,在这个问题的SSCCE)..

public class Form1 extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 
    Container content; 

public Form1()//constructor 
{ 
    super("TableLayout"); 
    content = getContentPane(); 
4

你举的例子都extends JFrame并具有-A JFrame。前者参考this;后者由frame