本文通過一個完整的 Java Swing 學生管理系統演示,涵蓋 GUI 佈局、事件監聽、數據存儲、查詢排序等核心桌面應用開發技能,適合 Java 初學者鞏固面向對象與事件驅動編程思想。
JTabbedPane tab = new JTabbedPane(JTabbedPane.TOP);
tab.add(p1, "成績錄入");
tab.add(p2, "成績查詢");
tab.add(p3, "成績排序");
private String[] name = new String[100];
private String[] grade = new String[100];
private int countNum = 0; // 當前記錄數
採用定長數組模擬列表存儲,簡化邏輯,適合教學演示。生產環境建議使用 ArrayList<Student>。
內部類 Listener implements ActionListener 統一處理所有按鈕事件:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) { /* 添加邏輯 */ }
else if (e.getSource() == b2) { /* 撤銷邏輯 */ }
else if (e.getSource() == sBut) { /* 查詢邏輯 */ }
else if (e.getSource() == sortBut) { /* 排序邏輯 */ }
else if (e.getSource() == clearBut) { /* 清空邏輯 */ }
}
// 添加
if (textName.getText().isEmpty() || textGrade.getText().isEmpty()) {
showLabel.setText("添加失敗(姓名、成績不能為空)!");
} else {
name[countNum] = textName.getText();
grade[countNum] = textGrade.getText();
countNum++;
refreshDisplay();
}
// 撤銷
if (countNum > 0) {
countNum--;
refreshDisplay();
}
for (int i = 0; i < countNum; i++) {
if (name[i].equals(searchName)) {
resultText.setText("姓名:" + name[i] + ", 成績" + grade[i]);
return;
}
}
resultText.setText("未找到該學生!");
for (int i = 0; i < countNum; i++) {
for (int j = i + 1; j < countNum; j++) {
if (Integer.parseInt(grade[i]) < Integer.parseInt(grade[j])) {
swap(name, i, j);
swap(grade, i, j);
}
}
}
refreshDisplay(true); // 更新排序頁顯示區
程序啟動後顯示主窗口,三分頁切換流暢,數據操作即時反饋。可擴展方向:
JTable 替換 TextArea,支持列排序/編輯SwingWorker 避免界面凍結這個小系統雖簡單,但完整踐行了「模型-視圖-控制器」分離思想,是通往 Java 桌面開發大門的敲門磚。