我对 JFrame 和关键字“this”有疑问。当我使用frame.getContentPane时,除非我用“this”替换frame,否则组件不会显示。看来 getContentPane 没有获取 JFrame 内容 Pane ,它获取了其他我不知道它是什么的东西。恐怕我有两个不同的 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();
}
}
最佳答案
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();
关于java - 使用 JFrame 时组件不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7266002/