当我更换屏幕时如何处理

时间:2011-08-27 11:49:00

标签: java swing

我尝试构建2类:LoginScreen类和MainScreen类

当我运行程序时,它将首先显示登录屏幕然后我使用用户名和密码登录主屏幕弹出,但登录屏幕不会消失。我不知道如何正确处理它。

因为我使用的方法是

  

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.");
   }
     

}

我知道这是愚蠢的代码和错误的实现方式,但是你可以引导我做出合适的代码。

1 个答案:

答案 0 :(得分:3)

我想这个方法是你的第一个屏幕的方法,它必须是JDialog或JFrame。只需致电setVisible(false)隐藏相框(如果对话框不再使用,您也可以拨打dispose()。)

此外,您不应该在JFrameExample上调用main方法。主方法通常用于启动新应用程序。只需执行main方法对您的动作侦听器执行的操作(可能是new JFrameExample().setVisible(true))。

最后,事件调度线程(EDT)中始终会调用事件侦听器,因此使用事件侦听器中的SwingUtilities.invokeLater毫无意义。

总结一下,这里是代码的样子:

if (isPasswordCorrect(input)) {
    setVisible(false); // or dispose();
    JFrame mainFrame = new JFrameExample();
    mainFrame.setVisible(true);
}