首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Swing 實作登入視窗與學生管理系統主介面完整範例

     編輯:程式設計綜合問答

需求分析

  • 登入視窗:帳號、密碼輸入欄,「登入」「重置」按鈕。
  • 登入成功開啟主視窗:選單列含「檔案」→「新增」「開啟」「儲存」「離開」。
  • 主視窗內容區域:學生資料表單/表格(CRUD)。

核心類別架構

LoginFrame      extends JFrame  // 登入視窗
MainFrame       extends JFrame  // 主視窗
Student         implements Serializable  // 學生實體
StudentDAO      // 資料存取介面 (檔案/資料庫)
StudentTableModel extends AbstractTableModel // JTable 模型

關鍵程式碼片段

1. 登入驗證與視窗切換

btnLogin.addActionListener(e -> {
    String user = txtUser.getText();
    String pwd = new String(txtPwd.getPassword());
    if (authenticate(user, pwd)) {
        dispose(); // 關閉登入視窗
        SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
    } else {
        JOptionPane.showMessageDialog(LoginFrame.this, "帳號或密碼錯誤");
    }
});

2. 主視窗選單列建構

JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("檔案");
fileMenu.add(new AbstractAction("新增") { public void actionPerformed(ActionEvent e) { clearForm(); }});
fileMenu.add(new AbstractAction("開啟") { public void actionPerformed(ActionEvent e) { loadFile(); }});
fileMenu.add(new AbstractAction("儲存") { public void actionPerformed(ActionEvent e) { saveFile(); }});
fileMenu.addSeparator();
fileMenu.add(new AbstractAction("離開") { public void actionPerformed(ActionEvent e) { System.exit(0); }});
menuBar.add(fileMenu);
setJMenuBar(menuBar);

3. 學生資料表格模型

class StudentTableModel extends AbstractTableModel {
    private List<Student> data = new ArrayList<>();
    private String[] cols = {"學號", "姓名", "性別", "出生日期", "電話"};
    
    public int getRowCount() { return data.size(); }
    public int getColumnCount() { return cols.length; }
    public String getColumnName(int c) { return cols[c]; }
    public Object getValueAt(int r, int c) { /* 依欄位回傳 */ }
    // 提供 add/remove/update 方法並 fireTableRowsInserted/Updated/Deleted
}

完整可執行專案下載

CSDN 下載資源:Java Swing 登入+學生管理系統完整原始碼

遷移建議

  • 教學/小型專案:Swing 即可,零依賴、跨平台。
  • 企業級桌面應用:考慮 JavaFX (現代 UI、FXML 分離、CSS 樣式) 或 Electron + Web 技術。
  • 資料持久化:檔案序列化 → SQLite (嵌入式) → MySQL/PostgreSQL (Client-Server)。

從經典 Swing 入手掌握事件驅動、MVC 分層、TableModel 等核心概念,為後續遷移現代框架打下堅實基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved