方法要放在构造函数里面:import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
public Test()
{ Container contentPane = getContentPane();
JPanel p = new JPanel();
contentPane.add(p,"Center"); JButton b = new JButton("sdf"); p.add(b);
}
public static void main(String[] args)
{
JFrame f = new Test();
f.show();
}
}

解决方案 »

  1.   

    contentPane.add(p,"Center");    p.add(b);你这两句代码位置放错了
    怎么可以放在定义变量初始化的地方呢
    调用、执行方法,其代码必须处于某个方法之内才行拉
    将这两行代码移到某个方法内即可,改动如下:
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame
    {
        public Test()
        {    }    Container contentPane = getContentPane();
        JPanel p = new JPanel();    JButton b = new JButton("sdf");public void ss() {
      contentPane.add(p,"Center");
        p.add(b);
    }    public static void main(String[] args)    {
          Test f = new Test();
            f.ss();
            f.show();
        }}
      

  2.   

    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame
    {
        public Test()
        {    }    Container contentPane = getContentPane(); JPanel p = new JPanel(); JButton b = new JButton("sdf"); {
    contentPane.add(p,"Center");
    p.add(b);
    }
        public static void main(String[] args)    {
          Test f = new Test();        f.show();
        }
    }
      

  3.   

    修改如下:
    class Test extends JFrame
    {
      Container contentPane = getContentPane();
      JPanel p = new JPanel();
      JButton b = new JButton("sdf");
      public Test()
      {
        p.add(b);
        contentPane.add(p,"Center");
      }
      public static void main(String[] args)
      {
        JFrame f = new Test();
        f.show();
      }
    }
      

  4.   

    public class  LifeInOrder
    {
    static helperForSee staticone = new helperForSee("I'm static one");
    helperForSee normalone = new helperForSee("I'm normal one");
    static
    {
    System.out.println("I'm in static block");
    }
    {
    System.out.println("I'm in normal block");
    } public LifeInOrder()
    {
    System.out.println("I'm in LifeInOrder Constructor");
    } public static void main(String[] args) 
    {
    System.out.println("Hello World!");
    new LifeInOrder();
    }
    }
    class helperForSee
    {
    public helperForSee(String str)
    {
    System.out.println(str);
    }
    };运行这个小示例,你就应该知道一个类初始化的顺序,你写的类违反了类的初始化规则! 你可以参照楼上几位的修改方法和意见!