我对初始化像JTextField和其他组件的Swing组件感到困惑。从DoSth类调用,getTxtUser返回空指针异常,而如果来自其自己的类的getTxtUser()返回正确的值。请帮助我。谢谢 代码:
public class GUI{
private JLabel lblUname;
private JTextField txtUname;
public void showGUI(){
lblUname = new JLabel("Username");
txtUname = new JTextField(20);
....................
}
public String getTxtUser(){
return this.txtUname.getText();
}
}
public class DoSth(){
..............
GUI g = new GUI();
String user = g.getTxtUser(); //null pointer Exception even if it has some value
...............
}
答案 0 :(得分:2)
txtUname
未在构造函数中初始化,因此调用方法getTxtUser
形式DoSth
类会导致NPE。在构造函数中移动GUI组件初始化或调用showGUI
方法初始化它们。
GUI g = new GUI();
g.showGUI();
String user = g.getTxtUser();