我对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