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

无法从java swing中的静态上下文错误引用非静态方法getContentPane(),java,swing,Java,Swing,无法从java swing中的静态上下文错误引用非静态方法getContentPane() 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 = getCo

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

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);
                ^

您需要从静态上下文转到非静态上下文。最简单的方法是创建类的实例,并调用方法,例如
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);
    }

}

这个错误信息几乎就是一个答案。请反复阅读。为什么要从主方法尝试它。jFrame必须是主线程的子线程。没错,您不能从静态方法调用任何非静态方法。您不能从静态方法调用非静态方法,因为它们根本不存在。非静态方法仅在对对象调用时存在。您需要在构造函数(对于初学者)或对象的方法中执行您试图执行的操作,然后在mainK中创建对象/调用方法。谢谢你的回答,不客气。记住,如果你觉得答案有用,请接受它(绿色勾号)。PS:这里还有一个输入错误:
c.add(sun)