gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:30:47 26 4
gpt4 key购买 nike

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

最佳答案

您需要从静态上下文转到非静态上下文。最简单的方法是创建类的实例,然后调用方法,例如

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

}

关于java - java swing 中的非静态方法 getContentPane() 无法从静态上下文错误中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com