当前位置: 动力学知识库 > 问答 > 编程问答 >

authentication - How to prevent a window to load if it has not previously gone through the stage of login in Java?

问题描述:

I have made a program in Java that has two windows (JFrames):

a) The Log-in Window,

b) The Main Window.

The correct way to run the program is to run first the "Log-in Window" and if the username and password are correct, then this window redirects you to the "Main Window", making the "Log-in Window" to dispose.

BUT

If someone runs directly the "Main Window" (ignoring the Log-in stage), then this window will run correctly without any authentication...

SO

How can I prevent the "Main Window" from loading and running if someone runs it directly (e.g.>> java Main_Window)? I want my program to run only with the order (1) "Log-in Window" and then (2) "Main Window".

EDIT

The Main_Window class has only one main method with the below code:

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

final Main_Window frame = new Main_Window();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

toRunOnClose();

frame.dispose();

}

});

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

网友答案:

Suggestions:

  • Your login window should be a modal dialog, such as a JDialog, not a JFrame.
  • Your GUI should have only one main method, the method that calls your login modal dialog first, and then if successful, opens the main JFrame after this.

The main main method could look something like:

   private static void createAndShowGui() {
      LoginDialog loginDialog = new LoginDialog();
      loginDialog.setVisible(true);

      // however you verify that the user is authentic
      if (loginDialog.verify()) {
         MainGui mainGui = new MainGui();
         mainGui.setVisible(true);
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

In the example above, since LoginDialog is modal, the code below loginDialog.setVisible(true) is not run until the dialog window is no longer visible.


Regarding your questions:

1) Run some code at the loading time of the main window,

Run it in the single one main method.

2) How can i set the look and feel (later) without a main method

You'll have a main method, but only one main method.

3) How can I run some code when the frame closes (as i already doing now)?

Do the same thing but in a single main method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: