核心代碼
// 在登入按鈕事件處理中
MainMenuGUI mainMenu = new MainMenuGUI(); // 實例化目標視窗類
mainMenu.setVisible(true); // 顯示目標視窗
this.dispose(); // 可選:關閉當前登入視窗
完整範例結構
// LoginFrame.java
public class LoginFrame extends JFrame {
public LoginFrame() {
JButton btnLogin = new JButton("登入");
btnLogin.addActionListener(e -> {
new MainMenuFrame().setVisible(true);
this.dispose();
});
add(btnLogin);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
// MainMenuFrame.java
public class MainMenuFrame extends JFrame {
public MainMenuFrame() {
add(new JLabel("歡迎進入主選單"));
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
注意事項
- 避免建立多個
JFrame 導致資源浪費,主流程建議單 JFrame + CardLayout 切換面板。
- 若需傳遞資料 (如用戶名),透過構造函數或 Setter 注入目標視窗。
- 確保在 EDT (事件調度執行緒) 中操作 Swing 組件,
setVisible(true) 已自動處理。