在 Swing 應用中實現窗口切換(如登錄成功跳轉主界面)的核心邏輯是:將當前窗體設置為不可見,同時創建並顯示新窗體。下面給出最小化代碼示例。
// 當前窗體(如登錄框)內的事件處理中
this.setVisible(false); // 隱藏當前窗體
JFrame newFrame = new JFrame(); // 創建新窗體(主界面)
newFrame.setTitle("主界面");
newFrame.setSize(800, 600);
newFrame.setLocationRelativeTo(null); // 居中
// 添加新窗體組件、佈局等初始化代碼...
newFrame.setVisible(true); // 顯示新窗體
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 關閉退出程序
public class LoginFrame extends JFrame {
public LoginFrame() {
setTitle("登錄");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("登錄");
btn.addActionListener(e -> {
this.setVisible(false);
new MainFrame().setVisible(true);
});
add(btn);
}
}
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("主界面");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 初始化主界面組件...
}
}
JFrame 實例,考慮使用 CardLayout 或 JDialog 管理多視圖。EXIT_ON_CLOSE,否則程序不會退出。