如何从验证类访问JFrame输入字段对象

问题描述

我已经创建了一个带有注册字段(名字,姓氏,电子邮件等)的GUI,并且我的GUI类是-

public class Registration extends JFrame {

    public static void main(String[] args) {
        try {
            Registration regform = new Registration ();
        } catch (Throwable e) {
            //
        }

      public Registration () {
            firstName = new JTextField();
            latName = new JTextField();
            btnRegistration = newJButton("Register");

            btnSubmit.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent arg0) {
                  //want to do something similar as below
                  //Validatefields Vf = new Validatefields(Registration Rg);
             }
            });

       }
}

现在,我想创建一个单独的类,以在单击“注册”按钮时验证所有字段。我是Java编码的新手,无法从验证类访问所有输入字段注册类的对象。

请注意,“类注册”和“验证字段”在同一软件包中。

public Class Validatefields{
    public static void Validattion(Registration Rg){
      //here I want access the text field as below
      //String Name = "Object of Registration Class".firstName.getText();

        
        int validateFlag = 0;
        if(Name.equal("")){
          validateFlag = 1;
        }
        if(validateFlag==0){
            ApiCall APC = new ApiCall();
            APC.RequestAccessToken();
        }
   }
}

在接下来的步骤中,我想使用另一个类在成功验证时调用API-因此,在这种方法中,我需要获取所有输入字段的值。

public Class ApiCall {
   public static void RequestAccessToken(){
      //Similarly I want to get the individual field value here and pass it in the API
   }
}

我试图从互联网的不同来源阅读类似的示例,但无法弄清楚。任何帮助都将非常棒。

解决方法

现在,我想创建一个单独的类,以在单击“注册”按钮时验证所有字段。

这是一个非常好的主意,您可以采用一般的方法。我认为主要问题是您的语法不正确。但是,在此之前,我的建议是将字段传递给构造函数,而不是整个Registration对象:

public static void Validattion(JTextField firstName,JTextField lastName){

现在,您通过将字段传递给构造函数来创建实例:

Validatefields Vf = new Validatefields(firstName,lastName);

请注意,您仅在此处使用变量名,而不是类型。这很可能是您遇到的主要问题,并导致尝试中的错误。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...