0

我对初始化 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
     ...............
 }
4

1 回答 1

2

txtUname没有在构造函数中初始化,因此调用getTxtUser表单DoSth类的方法会导致 NPE。要么在构造函数中移动你的 GUI 组件初始化,要么调用 showGUI方法来初始化它们。

GUI g = new GUI();
g.showGUI();
String user = g.getTxtUser(); 
于 2013-11-04T04:09:44.597 回答