0

I want to connect my IDE to Oracle SQL Developer. Therefore I have to use this line of code:

Connection connection = DriverManager.getConnection(dbURL, username, password);

To enter the password I am using this:

JPasswordField pass = new JPasswordField(10);

I would like to know how I can convert this JPasswordField into a String, so I can use the "Connect" line of Code I(This line only works with Strings)

EDIT: This is the code for entering the password. I found it here on stackoverflow:

JPanel panel = new JPanel();
      JLabel label = new JLabel("Enter password:");
      JPasswordField pass = new JPasswordField(10);
      panel.add(label);
      panel.add(pass);
      String[] options = new String[]{"OK", "Cancel"};
      int option = JOptionPane.showOptionDialog(null, panel, "      Password for Database Connection",
                               JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
                               null, options, options[0]);
  • `new String(pass.getPassword())`. – MC Emperor Jul 20 '22 at 14:43
  • This does not work. In this line "getConnection" is underlined red because "pass" is not a String...? Connection connection = DriverManager.getConnection(dbURL, username, pass); – singhKirat Jul 20 '22 at 16:20
  • No, because `pass` is a `JPasswordField`. As I said, `new String(pass.getPassword())` yields the contents of the password field as a `String`. – MC Emperor Jul 20 '22 at 16:37

3 Answers3

1

You just simply cast the the pass.getPassword() into string like this:

String stringPass = new String(pass.getPassWord());

but that defeats the security purpose of JPasswordField. Make sure to overwrite the pass.getPassWord() which is of type char[] since String stays in the JVM (Java Virtual Machine) until it's garbage-collected.

camelCase
  • 43
  • 5
0
String passText = new String(pass.getPassword());

See Link for more information.

ag00se
  • 116
  • 1
  • 10
0

I guess you will have some kind of submit button somewhere which will call the method doing the connection.

You will be able to retrieve the content of the JPasswordFieldby calling the getPassword method which provide a char[].

Converting from char[] can be done by calling String.valueOf

Julien
  • 2,256
  • 3
  • 26
  • 31