Java Reference
In-Depth Information
centerPanel . setLayout(
new
GridLayout (2 , 2) ) ;
JLabel label1 =
new
JLabel(
"login: "
);
centerPanel .add( label1) ;
final
JTextField loginField =
new
JTextField(
""
, 10) ;
centerPanel .add(loginField);
JLabel label2 =
new
JLabel(
"passowrd: "
);
centerPanel .add( label2) ;
final
JPasswordField passwordField =
new
JPasswordField(
""
, 10) ;
centerPanel .add(passwordField) ;
add(centerPanel , BorderLayout .CENTER) ;
JPanel southPanel =
new
JPanel () ;
add(southPanel , BorderLayout .SOUTH) ;
JButton okButton =
new
JButton(
"OK"
);
southPanel .add(okButton) ;
okButton. addActionListener(
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
char
[] correctPassword =
;
if
(loginField .getText() .trim() . equals(
"java"
))
{
char
[ ] password = passwordField . getPassword() ;
if
(Arrays . equals(password , correctPassword))
{
LoginDialog .
this
.dispose();
{
'f'
,
,
'n'
}
'u'
}
}
Arrays . f i l l (correctPassword ,
'0'
);
}
}
);
}
}
}
Note that the constructor of the
LoginFrame
class first makes the window visible. We
need to display the window early because the call to create the dialog window is
blocking
.
In other words, if we do not display the window initially, it will be displayed only after the
dialog window is closed.
The code in the constructor of the
LoginDialog
class creates two panels. The top
panel has a two-by-two grid layout and is in the center part of the dialog. It displays
two labels and two text fields that store the login and the password. An
OK
button is
displayed in a panel at the south. When the
OK
button is pressed, the code checks if
the correct login and password is entered. Only when this is the case will dialog win-
dow close. The line
LoginDialog.this.dispose()
means execute the
dispose
method
for the outer object. Of course, since the local anonymous class does not contain a
dispose
method, we could have rewritten the line as just
dispose()
. In order to pre-
vent the dialog from closing any other way, we have made it modal and added the line
setDefaultCloseOperation(JDialog.DO NOTHING ON CLOSE)
. The last statement simply
means that the dialog window will not close when the user presses the X in the top right
corner.
Note that there is a
getText
method for the
JPasswordField
class, which retrieves the
password as a string. However, for security reasons, the method is
deprecated
. It was replaced
by the
getPassword
method, which retrieves the password as an array of characters. For
security reasons, Java decided that the second method is recommended. The
Arrays.equals
method compares two arrays using deep comparison. In other words, it checks if the arrays
have the same content. Lastly, the line
Arrays.fill(correctPassword, '0' )
fills the
correctPassword
array with zeros. This is done so that no one can examine the main
memory and see the correct password. Of course, the presented code is not bulletproof. An