使用JFrame时,组件不会显示

时间:2011-09-01 04:02:08

标签: java swing jframe

我遇到了JFrame和关键字“this”的问题。当我使用frame.getContentPane时,除非我用“this”替换frame,否则组件不会显示。似乎getContentPane没有得到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();
    }
}

2 个答案:

答案 0 :(得分:4)

您的示例extends JFrame和has-a JFrame。前者由this引用;后者由frame

答案 1 :(得分:4)

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

您的班级框架,并且还有一个名为Frame的{​​{1}}属性。当然有两个框架!

改变这个..

frame

更喜欢的东西(问题中带有SSCCE的明确答案)..

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
{