blablaguy
blablaguy

Reputation: 11

Dynamically Creating Objects in a Class from String

I'm trying to make a Sign Up window on JFrame Form in NetBeans. I have created a class named users (in the same package) that has a username as String and password as char[].

When the username and password are filled, and Sign Up button is pressed, I want to make a new object in the class 'users' so that it's name is taken from username textfield itself.

I want to dynamically create object whose names have been taken from a string.

eg: If I put value of Username as "guy", then create users.guy which has a String = "guy" and a char[] as password.

package login;

public class users {
    private char[] password;
    String username;

    users() {
        username = "anonymous";
        password = null;
    }

    users(String u, char[] p) {
        username = u;
        password = p;
    }

    void putdata() {
        System.out.println(username);
        System.out.println(password);
    }
}

Thanks in advance.

Upvotes: 0

Views: 140

Answers (2)

Yayotrón
Yayotrón

Reputation: 1859

If I understand good your question what you want to do is a mapping. In Java there's a lot of ways for do that.

I would recommend you the use of HashMap, it's simple and efficient. There's a simple example.

String userYayotrón = "Yayotrón";
char[] passwordYayotrón = "contraseña".toArray();
Map<String, char[]> usersMap = new HashMap<String, char[]>();
//This hashmap will take two values, the KEY which identifies the VALUE. The key is the first one, which I define as String. I will use it for save the User's name. And the value will be the password.
usersMap.put(userYayotrón,passwordYayotrón);

Now, you can use this map for a lot of things. For example:

usersMap .get(userYayotrón); // This will return an char[] with the password of Yayotrón.
usersMap .size(); // How many users do you have in this map.

Also I highly recommend read the following question related:

Upvotes: 1

Jonathan Beaudoin
Jonathan Beaudoin

Reputation: 2188

Create a new instance of the users class passing the username and password like so:

new users(userTextField.getText(), userPasswordField.getText().toCharArray())

If you include the code for the GUI itself I'd be able to give you a more direct answer/solution.

Upvotes: 0

Related Questions