非循环方法getContentPane()无法从java swing中的静态上下文错误中引用

时间:2014-09-19 12:30:06

标签: java swing

非静态方法getContentPane()无法从java swing中的静态上下文错误中引用

import javax.swing.*;
import java.awt.*;
import java.awt.Component;
import java.awt.event.*;

public class Studentlogin extends JFrame{
   public static void main(String[] args) {

    Container c = getContentPane();

    setTitle(" Staff Signin ");
    setSize( 400 , 300);
    setLayout(new FlowLayout());    
    setVisible(true);
    setLayout(null);

    JLabel tun = new JLabel("UserName");
    tun.setBounds(10,10,140,25);
    c.add(sun);

    JTextField tuname = new JTextField(10);
    tuname.setToolTipText("Enter your StaffId ");
    tuname.setBounds(145,10,200,25);
    c.add(tuname);

    JLabel tpw = new JLabel("PassWord");
    tpw.setBounds(10,50,140,25);
    c.add(tpw); 

    JPasswordField tpword = new JPasswordField(10);
    tpword.setEchoChar('*');
    tpword.setBounds(145,50,200,25);
    c.add(tpword);
}
}

在编译时,我得到这种类型的错误,任何人都可以找到我这个代码的错误,因为我可以在actionlistrener段中执行相同类型的代码格式

Studentlogin.java:9: error: non-static method getContentPane() cannot be referen
ced from a static context
                Container c = getContentPane();
                              ^
Studentlogin.java:11: error: non-static method setTitle(String) cannot be refere
nced from a static context
                setTitle(" Staff Signin ");
                ^
Studentlogin.java:12: error: non-static method setSize(int,int) cannot be refere
nced from a static context
                setSize( 400 , 300);
                ^

1 个答案:

答案 0 :(得分:1)

您需要从静态环境转变为非静态环境。最简单的方法是创建一个类的实例,并调用一个方法,例如go

public class Studentlogin extends JFrame{
    public static void main(String[] args) {
        new Studentlogin().go();
    }

    private void go() {
        Container c = getContentPane();

        setTitle(" Staff Signin ");
        setSize( 400 , 300);
        setLayout(new FlowLayout());
        setVisible(true);
        setLayout(null);

        JLabel tun = new JLabel("UserName");
        tun.setBounds(10,10,140,25);
        c.add(sun);

        JTextField tuname = new JTextField(10);
        tuname.setToolTipText("Enter your StaffId ");
        tuname.setBounds(145,10,200,25);
        c.add(tuname);

        JLabel tpw = new JLabel("PassWord");
        tpw.setBounds(10,50,140,25);
        c.add(tpw);

        JPasswordField tpword = new JPasswordField(10);
        tpword.setEchoChar('*');
        tpword.setBounds(145,50,200,25);
        c.add(tpword);
    }

}