2011-09-01 31 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