简体   繁体   English

如何使用存储在辅助类中主类中的Strings值? (有关详细信息,请参见描述。Java)

[英]How can I use the Strings values stored in a main class in my secondary class? (see description for details. Java)

I got a class MainClassTestPrompts that asks the user for username and password using an input box and then it stores each value on it's individual Strings. 我得到了一个MainClassTestPrompts类, 该类使用输入框询问用户的用户名和密码,然后将每个值存储在单独的字符串中。

import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class MainClassTestPrompts {

    public static void main(String[] args) {

        JTextField username = new JTextField();
        JTextField password = new JPasswordField();
        Object[] DBInputBox = { "Username:", username, "Password:", password };

        try {

            // I. Username and Password Prompts
            JOptionPane.showConfirmDialog(null, DBInputBox, "Login", JOptionPane.OK_CANCEL_OPTION);

            String Username = username.getText();
            String Password = password.getText();

            System.out.println("Username: " + Username);
            System.out.println("Password: " + Password);

        } catch (Exception e) {
            System.out.println(e);

        } 

    }
}

Then I have another class SecondaryClass , that will perform a set of actions and then it will need the stored strings: Username and Password to perform actions. 然后,我有另一个类SecondaryClass ,它将执行一组操作,然后将需要存储的字符串: UsernamePassword以执行操作。

My issue is that I got no idea how to just grab the stored strings values in the main class and use them in the secondary class WITHOUT getting the prompt again. 我的问题是我不知道如何只获取主类中存储的字符串值,然后在辅助类中使用它们而又不会再次得到提示。 I want to run my main class, get the user/pass, then eventually run the second class and that class will pick the stored values. 我想运行我的主类,获取用户/密码,然后最终运行第二个类,该类将选择存储的值。

What I have tried on the second class 我在第二堂课上尝试过的

public class SecondaryClassUseCredentials extends MainClassTestPrompts {

    public static void main(String[] args) {

        MainClassTestPrompts.main(null); // this will just run the MainClassTestPrompt which is not what I want.

        String Username = MainClassTestPrompts.Username; //I know this is wrong but is sort of what I'm looking for... 
        String Password = MainClassTestPrompts.Password;

    }

I will assume you are very new to Java and maybe programming else it is difficult to explain your design decisions. 我将假设您对Java还是很陌生,也许对编程而言,否则很难解释您的设计决策。

For a start, you got one design principle right: a class should do one thing. 首先,您有一个正确的设计原则:一个类应该做一件事。 So your MainClassTestPrompts prompts for the username and password and your SecondaryClassUseCredentials wants to do something with those. 因此,您的MainClassTestPrompts会提示您输入用户名和密码,而SecondaryClassUseCredentials希望对它们进行处理。 This is called the separation of concerns. 这称为关注点分离。

The mistake is to use main in both, or to use a method with no return type. 错误是在两者中都使用main ,或者使用没有返回类型的方法。 As main is used as the application entry point it would be better not to use main in these two classes at all -- they are parts of business logic and application wiring should be yet another concern. 由于将main用作应用程序的切入点,因此最好不要在这两个类中都使用main -它们是业务逻辑的一部分,应用程序接线应该是另一个问题。

So what you can do is to define one class/method pair that asks for credentials and returns those and the other one that calls the former and uses its result. 因此,您可以做的是定义一个类/方法对,它要求提供凭据并返回它们,而另一对则调用前者并使用其结果。 Doing one step at a time I will preserve static methods and introduce no interfaces even though this is what I would normally suggest: 一次只执行一个步骤,即使我通常建议这样做我也将保留静态方法并且不引入任何接口:

class MainClassTestPrompts {

   static Map.Entry<String, String> askForCredentials() {
        JTextField username = new JTextField();
        JTextField password = new JPasswordField();
        Object[] DBInputBox = { "Username:", username, "Password:", password };

        JOptionPane.showConfirmDialog(null, DBInputBox, "Login", JOptionPane.OK_CANCEL_OPTION);
        return new SimpleEntry<>(username.getText(), password.getText());
    }
}

Now your caller class may look like this: 现在您的呼叫者类可能如下所示:

class SecondaryClassUseCredentials {

   static void doSomething() {
        Map.Entry<String, String> credentials = MainClassTestPrompts.askForCredentials();
        String username = credentials.getKey();
        String password = credentials.getValue();
        ...
    }
}

For the next iteration, try getting rid of statics and use interfaces. 对于下一次迭代,请尝试摆脱静态变量并使用接口。 To leave you something to try on your own I will only suggest how the SecondaryClassUseCredentials may look like: 为了让您自己尝试一下,我只会建议SecondaryClassUseCredentials如下所示:

class SecondaryClassUseCredentials {

   private final Supplier<Map.Entry<String, String>> credentialsSupplier;

   SecondaryClassUseCredentials(Supplier<Map.Entry<String, String>> credentialsSupplier) {
       this.credentialsSupplier = credentialsSupplier;
   }

   static void doSomething() {
        Map.Entry<String, String> credentials = credentialsSupplier.get();
        String username = credentials.getKey();
        String password = credentials.getValue();
        ...
    }
}

in MainClassTestPrompt variable declaration should be before try catch block then it will work. 在MainClassTestPrompt中,变量声明应该在try catch块之前,然后它将起作用。 As you wrote it variables String Username; String Password 在编写时,变量为String Username; String Password String Username; String Password arelocal to try catch and you cannot access them from SecondaryClass. String Username; String Password本地的,可以尝试捕获,您不能从SecondaryClass访问它们。

 public class MainClassTestPrompts { //Better private String Username; private String Password; public String getUsername(){ return this.Username; } public String getPassword(){ return this.Password; } public static void main(String[] args) { JTextField username = new JTextField(); JTextField password = new JPasswordField(); Object[] DBInputBox = { "Username:", username, "Password:", password}; //Not ideal but will work try { // I. Username and Password Prompts JOptionPane.showConfirmDialog(null, DBInputBox, "Login", JOptionPane.OK_CANCEL_OPTION); //Edited Username = username.getText(); Password = password.getText(); System.out.println("Username: " + Username); System.out.println("Password: " + Password); } catch (Exception e) { System.out.println(e); } } } 

then call in Secondary 然后在中学

 public class SecondaryClassUseCredentials extends MainClassTestPrompts { public static void main(String[] args) { MainClassTestPrompts.main(null); // this will just run the MainClassTestPrompt which is not what I want. String Username = MainClassTestPrompts.getUsername(); //I know this is wrong but is sort of what I'm looking for... String Password = MainClassTestPrompts.getPassword(); } 

your code for the SecondClass will work too if you only want to use inheritance, as you extending the MainClass. 如果在扩展MainClass时只想使用继承,那么SecondClass的代码也将起作用。 But if you want to use Password and Username anywhere else better to write proper get() methods. 但是,如果您想在其他任何地方使用密码和用户名,则最好编写适当的get()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Android 中,多部分实体是否也用于下载文件,因为我看不到 class 的任何示例或详细说明 - In Android Does multipart entity is used for download file too as I can't see any example or details description for that class 我不知道如何做一个数组来存储每个学期的详细信息。 我应该创建 class Student 的子类 - I don't know how to do an array to store for each semester the details. I am supposed to create a subclass of the class Student 如何在主类中访问Java中的类 - How do I access a Class in Java in my main class Java-如何将对象从自己的类转换为主类中的字符串? - Java - How can I convert an object from my own class to a string in the main class? 为什么我的主类看不到其主方法? - Why can my main class not see its main method? 如何在我的Android项目中使用第二个Java类? - How can I use a second Java class in my Android project? 如何在 Java 中将链接列表与我的处理程序 class 一起使用? - How can I use a Linked list with my Handler class in Java? 我怎样才能将数组称为主类? - How can I call my array to my main class? 我想在我的主类/Java minecraft Paper 插件上使用我的其他类包括监听器 - I want to use my other class includes listener on my main class / Java minecraft Paper plugin 如何从 Java 中 Main 类的相对路径读取文件? - How can I read a file from a path relative of my Main class in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM