非静态方法的getContentPane()不能从静态上下文错误中的Java Swing引用
非静态方法的getContentPane()不能从静态上下文错误中的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);
^
你需要从静态到去非静态上下文中执行这个代码相同类型的格式。最简单的方法是创建你的类的实例,并调用一个方法,例如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);
}
}
主体中的方法。感谢您的回复 – Amir 2014-09-19 12:41:59
不客气。如果您觉得有用,请记住请接受答案(绿色勾号)。 – vikingsteve 2014-09-19 12:43:05
PS:您在这里也有一个错字:'c.add(sun);' – vikingsteve 2014-09-19 12:43:35
该错误消息几乎是一个答案。请一遍又一遍地阅读。 – 2014-09-19 12:30:47
你为什么试图从主要方法.. jFrame必须我主线程的子线程.. – Lijo 2014-09-19 12:32:24
这是正确的,你不能从静态方法调用任何非静态方法。 – justrohu 2014-09-19 12:32:45