2010-02-22 66 views
2

即時通訊創建一個Java應用程序與NetBeans。我有兩個用於登錄和主應用程序的jframes。我想要做的是在運行時加載登錄jframe,然後在用戶認證正確時加載主應用程序jframe。在主應用程序jframe已經加載之後,必須銷燬登錄jframe的實例。另外,我希望將來自登錄jframe的用戶信息傳遞給主應用程序jframe。我如何實現這個目標?多個JFrames

+0

您可能需要考慮在登錄窗口中使用JDialog而不是JFrame。 – Kylar 2010-02-22 19:10:50

回答

1

擴展JFrame以創建主框架。在此添加一個構造函數來接受用戶信息。

從登錄屏幕上,當驗證成功時,通過傳遞登錄信息創建Main框架的一個實例。在登錄框架上調用dispose()並在主框架上調用setVisible(true)

MainFrame mainFrame = new MainFrame(userInput.getText()); 
this.dispose(); 
mainFrame.setVisible(true); 
+0

不會this.dispose()也破壞mainFrame? – mixm 2010-02-22 11:15:30

+0

這段代碼必須駐留在登錄幀內。 – 2010-02-22 11:25:46

+0

是的,但大型機的實例在登錄框架中找到 – mixm 2010-02-22 11:36:28

3

我建議以下簡單的方法,從而創建類來表示您的登錄面板和主應用程序框架。在這個例子中,我創建了一個登錄面板,而不是一個框架,以允許它嵌入模態對話框中。

// Login panel which allows user to enter credentials and provides 
// accessor methods for returning them. 
public class LoginPanel extends JPanel { 
    public String getUserName() { ... } 

    public String getPassword() { ... } 
} 

// Main applicaiton frame, initialised with login credentials. 
public class MainFrame extends JFrame { 
    /** 
    * Constructor that takes login credentials as arguments. 
    */ 
    public MainFrame(String userName, String password) { ...} 
} 

// "Bootstrap" code typically added to your main() method. 
SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
    LoginPanel loginPnl = new LoginPanel(); 

    // Show modal login dialog. The code following this will 
    // only be executed when the dialog is dismissed. 
    JOptionPane.showMessageDialog(null, loginPnl); 

    // Construct and show MainFrame using login credentials. 
    MainFrame frm = new MainFrame(loginPnl.getUserName(), loginPnl.getPassword()); 
    frm.setVisible(true); 
    } 
});