I try build the 2 Class: LoginScreen Class and MainScreen Class
When I run program it will show the login screen first then I use username and password to login the Mainscreen are pop-up but the login screen doesn’t disappear.I am not sure how to handle it correctly.
Because the method I use is
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();if (OK.equals(cmd)) { //Process the password. char[] input = passwordField.getPassword(); if (isPasswordCorrect(input)) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrameExample.main(null); } }); } else { JOptionPane.showMessageDialog(controllingFrame, "Invalid password. Try again.", "Error Message", JOptionPane.ERROR_MESSAGE); } //Zero out the possible password, for security. Arrays.fill(input, '0'); passwordField.selectAll(); resetFocus(); } else { //The user has asked for help. JOptionPane.showMessageDialog(controllingFrame, "You can get the password by searching this example's\n" + "source code for the string \"correctPassword\".\n" + "Or look at the section How to Use Password Fields in\n" + "the components section of The Java Tutorial."); }}
I know this is the stupid code and wrong way to implement it but can you guide me to make the appropriate one.
I guess this method is a method of your first screen, which must be a JDialog or a JFrame. Just call
setVisible(false)to hide the frame (you may also calldispose()if the dialog won’t be used anymore).Also, you shouldn’t call the main method on JFrameExample. A main method is normally used to start a new application. Just do what the main method does from your action listener (probably
new JFrameExample().setVisible(true)).Finally, an event listener is always invoked in the event dispatch thread (EDT), so there is no point in using
SwingUtilities.invokeLaterfrom an event listener.To recap, here’s how the code should look like: