我對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();
}
}
可悲的是,我已經做了不止一次,而這重多-factoring。 :-) – trashgod