1

I was experimenting with JOptionPane in Java and I want to make a simple password program. Upon creating it, I wanted to implement a password autosave function. I do not know the method that actually accesses the text box (the area where you enter text).

import javax.swing.JOptionPane;

public class passWord_GUI {

    public static void main(String[] args) {
        String username = JOptionPane.showInputDialog("Enter username");
        String password = JOptionPane.showInputDialog("Enter password");
        //password.setTheConentOfTheTextBox(passwordSave);
        //Set up the UI.
        if (username != null
                && password != null
                && username.equals("asdf")
                && password.equals("swordfish")) {
            JOptionPane.showMessageDialog(null, "You're in!");
            String passwordSave = "swordfish";
        } else {
            JOptionPane.showInternalMessageDialog(null, "Wrong! Try again.");
        }
    }
}

I just want to know a way to edit the contents of the text box without having to actually type something in it. In this case, write a password.

You're help is appreciated!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Read the JOptionPane API. You will find a link to the Swing tutorial on `How to Use Option Panes` that gives you example of using an input dialog. – camickr Nov 21 '13 at 06:02

1 Answers1

1

There's probably way to achieve this, but I would imagine it would a little messy.

A lot of people foget that the JOptionPane API is very flexible. If you pass it a Component for example, that component will be added to the JOptionPane.

This allows you the opportunity to provide complex user interfaces to the API.

Basically, what I would do in you case is create a "Login Panel", which contained the user name and password fields (you could use a JPasswordField to "hide" the password as the user types). This panel would also load the stored password.

You would then pass this to the JOptionPane as the message object. When the user closes the dialog and you've determine that the selected the "Ok" button, you could extact the values from the "Login Panel" and proceed as you need...

For example, see Java Text Field of form to new form

Take a look at How to make dialogs for more details

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366