-1

我有两个 JAVA 文件和两个公共类在其中我在 File1.java 中获取用户名,然后需要在 File2.java 中使用它,所以基本上我需要从 File1.java 中的用户获取用户名,然后将其传递给 File2 .java 进行处理。

现在我完成了使用 File1.java 从用户获取用户名的部分,但不知道如何将其提供给 File2.java 进行处理。这就是我从 File1.java 中的用户获取用户名并将其存储到变量用户中的方式。现在我需要将此用户数据移动到 File2.java。

    String user = jTextField1.getText();

所以请帮助我将用户名数据从 File1.java 传递到 File2.java

4

4 回答 4

1

What you need is to pass it to File2.java, so assuming that you have something like so:

public class File2
{
    ...
    //Constructor
    public File2(...)
    ...
}

You would need to change it like so:

public class File2
{
    ....
    String userName = "";
    public File2(...String userName...)
    {
        this.userName = userName;
        ...
    }
    ....
}

And call it like so (from your File1 class):

String user = jTextField1.getText();
...
File2 file2 = new File2(..., user, ...);

Alternatively, instead of passing the userName field, you can pass an instance of File1 to your File2 class and expose whatever fields you want to access through Field2 by creating the appropriate get methods in your File1 class. This usually comes in handy when you need to access more than one field.

于 2013-03-27T14:21:26.203 回答
0

For sharing values across classes, you can make the variables as instance variables and have setters and getters to access them.

In your case, make user as a private instance variable of your class File1 and then in your File2 class, you can do something like :

public void someMethod(File1 f1Object){

  String s = f1Object.getUser();

}
于 2013-03-27T14:21:40.160 回答
0

File1.java 和 File2.java 是文件名,它们对于您正在讨论的内容并不重要。更重要的是你有两个 java 类。谈论他们的类名而不是文件名。

希望您还拥有两个(或更多)Java对象,对吗?也就是说,这些类的实例。

如果第二类的对象需要做一些处理,那么就需要在这个第二类中定义一个方法,像这样:

public void doSomeProcessing(String userName)
{
}

然后这样称呼它:

object2.doSomeProcessing(jTextField1.getText());

但是请给文件、类、对象和方法起有意义的名字!

于 2013-03-27T14:24:32.003 回答
0

您可以将它作为 a 传递parameter给类中存在的方法,File2也可以在类中使用 getter 方法并userFile1类中创建类的新实例File1并使用该实例File2调用getter

在文件 1

new File2().doSomethingMethod(user);

在文件 2 中

public void doSomethingMethod(String user){
    //user has the value you wanted to pass.
}
于 2013-03-27T14:20:10.967 回答