2

I cant not get the input from my JPasswordField. I'm getting it because it will be shown in a JOptionPane as an output(just for practice purposes).

Eclipse does not give me any errors but the program does not work correctly

Okay so here's the flow of the program. if the JPasswordField is equal to "admin". Then a dialog box will appear and will display my password (which is "admin"). That's it.

I already converted my JPasswordField into string. But still. there's no string to be displayed. There's no error to be displayed in Eclipse also.

Codes:

public class GUI2 extends JFrame {
private JButton shut;
private JPasswordField field;


public GUI2(){
    super("Display The Password");
    setLayout(new FlowLayout());

    field = new JPasswordField(10);
    add(field);
    display = new JButton("Display");
    add(display);


    thehandler handler = new thehandler();
    display.addActionListener(handler);




}

 class thehandler implements ActionListener{
    String password = new String(field.getPassword());

     public void actionPerformed(ActionEvent event){
         if (password.equals("admin")){

             JOptionPane.showMessageDialog(null, password);


         }


    }

}
}
jerome_mjt
  • 223
  • 2
  • 9
  • 2
    move the line ``String password = new String(field.getPassword());`` inside the ``actionPerformed`` method. – f1sh Nov 10 '16 at 09:15

3 Answers3

1

field.getPassword() returns char[], it is done for security (more detailed you can read here), according to this link it is not a good idea to convert it to String. You should compare like this:

char[] correctPassword = { 'a', 'd', 'm', 'i', 'n' };
Arrays.equals (field.getPassword(), correctPassword);
Community
  • 1
  • 1
D. Krauchanka
  • 244
  • 3
  • 14
1

Try with String.valueOf() method.

String str = String.valueOf(field.getPassword())

Read more details about String.valueOf() at https://www.tutorialspoint.com/java/java_string_valueof.htm

Harshil
  • 448
  • 1
  • 7
  • 27
1

The problem is that the variable password is initialized when your class thehandler is instantiated (new thehandler();). At this moment the password equals empty string. Then when you type the password and want to display it, it has not been refreshed.

Solution:

class thehandler implements ActionListener {
     public void actionPerformed(ActionEvent event){
         String password = new String(field.getPassword());
         if (password.equals("admin")){
             JOptionPane.showMessageDialog(null, password);
         }
     }
}

This way, each time you click on the display button (the actionPerformed method is call) you will retrieve the current value of the JPasswordField.


D. Krauchanka is right but it isn't why you can't get the text you type in the field. However you should consider his advice !

Max Steely
  • 36
  • 5