我对初始化 Swing 组件(如 JTextField 和其他组件)感到困惑。从 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
...............
}