简体   繁体   中英

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.

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.

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.

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. This is called the separation of concerns.

The mistake is to use main in both, or to use a method with no return type. 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.

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:

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. As you wrote it variables String Username; String Password String Username; String Password arelocal to try catch and you cannot access them from 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. But if you want to use Password and Username anywhere else better to write proper get() methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM