|
楼主 |
发表于 2024-1-5 15:11:17
|
显示全部楼层
@FishC
package com.example.javafxmw;
import DatabaseOperations.*;
import TeacherPostsSystem.*;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
public class HelloApplication extends Application{
//初始界面的账号输入框
public TextField accountField = new TextField("abc");
//初始界面的密码输入框
public PasswordField passwordField = new PasswordField();
//创建单选选项
public ToggleGroup toggleGroup = new ToggleGroup();
//选项,管理员登录
public RadioButton adminRadioButton = new RadioButton("管理员");
public RadioButton teacherRadioButton = new RadioButton("教师");
//基础界面使用borderPane布局
private BorderPane borderPane = new BorderPane();
//存放输入框
//执行和数据库相关的方法所用
public DatabaseConnect connect = new DatabaseConnect();
// 创建菜单栏
@Override
public void start(Stage stage) {
borderPane.getChildren().clear();
VBox vBox = new VBox();
vBox.setSpacing(10);
// 创建账号输入框
HBox accountBox = new HBox();
Label accountLabel = new Label("账号:");
accountBox.getChildren().addAll(accountLabel, accountField);
// 创建密码输入框
HBox passwordBox = new HBox();
Label passwordLabel = new Label("密码:");
passwordBox.getChildren().addAll(passwordLabel, passwordField);
// 创建登录按钮
Button loginButton = new Button("登录");
loginButton.setOnAction(actionEvent -> login());
// 创建注册按钮
Button registerButton = new Button("注册");
registerButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
// 获取当前选中的单选按钮
RadioButton selectedRadioButton = (RadioButton) toggleGroup.getSelectedToggle();
// 判断是否为教师选项
if (selectedRadioButton == teacherRadioButton) {
// 执行教师注册功能
register();
} else {
// 弹出提示框,告知不能进行管理员注册
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("不能进行管理员注册!");
alert.showAndWait();
}
}
});
// 创建单选按钮
adminRadioButton.setToggleGroup(toggleGroup);
adminRadioButton.setSelected(true); // 默认选中管理员登录
teacherRadioButton.setToggleGroup(toggleGroup);
// 将登录按钮和注册按钮添加到水平布局中
HBox buttonsBox = new HBox();
buttonsBox.getChildren().addAll(loginButton, registerButton);
buttonsBox.setSpacing(130);
// 将单选按钮添加到水平布局中
HBox radioButtonsBox = new HBox();
radioButtonsBox.getChildren().addAll(adminRadioButton, teacherRadioButton);
radioButtonsBox.setSpacing(100);
// 将控件添加到布局中
vBox.getChildren().addAll(accountBox, passwordBox, buttonsBox, radioButtonsBox);
BorderPane.setMargin(vBox, new Insets(180, 250, 180, 250));
// 设置vBox居中显示
borderPane.setAlignment(vBox, Pos.CENTER);
borderPane.setCenter(vBox);
Scene scene = new Scene(borderPane, 800, 640);
stage.setTitle("教师岗位管理系统");
stage.setScene(scene);
stage.show();
}
//登录方法
public void login() {
String currentAccountWorkId ;
// 获取用户输入的账号和密码,并去掉空白字符
String account = accountField.getText().trim();
String password = passwordField.getText().trim();
// 判断选择的身份
boolean isAdmin = toggleGroup.getSelectedToggle().equals(adminRadioButton);
String tableName = isAdmin ? "admin" : "teacher";
// 从对应的表中查询账号和密码
String sql = "SELECT * FROM " + tableName + " WHERE account = ?";
try (Connection conn = connect.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, account);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String dbPassword = rs.getString("password");
// 对用户输入的密码进行加密,比对数据库中的密码是否一致
if (password.equals(dbPassword)) {
// 登录成功,弹出提示框
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("登录成功!");
alert.showAndWait();
// 展示新的界面
if(isAdmin) {
showAdminScene();
}else {
currentAccountWorkId = getWorkIdByAccount(account);
showTeacherScene(currentAccountWorkId);
}
} else {
// 密码错误,弹出提示框
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("用户名或密码错误!");
alert.showAndWait();
}
} else {
// 账号不存在,弹出提示框
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("用户名或密码错误!");
alert.showAndWait();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private String getWorkIdByAccount(String account) {
String sql = "SELECT workid FROM teacher WHERE account = ?";
try (Connection conn = connect.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, account);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getString("workid");
} else {
return null;
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public void showTeacherScene(String currentAccountWorkId) {
// 清空之前的界面内容
borderPane.getChildren().clear();
try (Connection conn = connect.getConnection()) {
// 从teacher表和teacherinfomation表中联合查询教师信息,获取的信息是当前账户对应workid的信息
String sql = "SELECT t.id, t.account, t.password, ti.name, ti.gender, ti.age, ti.position, ti.worktime, ti.college "
+ "FROM teacher t LEFT JOIN teacherinformation ti ON t.workid = ti.workid "
+ "WHERE t.workid = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, currentAccountWorkId);
ResultSet rs = stmt.executeQuery();
// 获取列数,将获取到的列放到结果集中
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 创建表格
TableView<ObservableList<String>> table = new TableView<>();
// 添加表头,根据获取到的列,添加表头
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
/*
* ObservableList<String> 是每一行数据的类型,表示一行数据是一个字符串列表。 String 是单元格中数据的类型,
* 表示每个单元格中的数据是字符串类型。
*/
TableColumn<ObservableList<String>, String> column = new TableColumn<>(columnName);
// 设置表头内容居中,并设置内容只读
column.setCellValueFactory(
param -> new ReadOnlyObjectWrapper<>(param.getValue().get(table.getColumns().indexOf(column))));
table.getColumns().add(column);
}
// 添加数据行
while (rs.next()) {
ObservableList<String> data = FXCollections.observableArrayList();
for (int i = 1; i <= columnCount; i++) {
String cellValue = rs.getString(i);
// 处理空值
if (cellValue == null) {
cellValue = "无";
}
data.add(cellValue);
}
table.getItems().add(data);
}
// 创建ScrollPane并将表格放入其中
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(table);
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
// 将ScrollPane添加到BorderPane的中央
borderPane.setCenter(scrollPane);
// 创建按钮组
HBox buttonBox = new HBox(10);
buttonBox.setAlignment(Pos.CENTER);
//添加个人信息
Button personalInfoButton = new Button("添加个人信息");
personalInfoButton.setOnAction(actionEvent -> addPersonalInfo());
Button changePassWordButton = new Button("修改密码");
changePassWordButton.setOnAction(actionEvent -> changePassWord());
buttonBox.getChildren().addAll(changePassWordButton,personalInfoButton);
borderPane.setBottom(buttonBox);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addPersonalInfo() {
}
public void changePassWord() {
// 调用创建对话框的方法,并让用户输入要修改密码的教师账号
Optional<ArrayList<TextField>> result = createInputDialog("修改密码", "请输入账号");
if (result.isPresent()) {
ArrayList<TextField> idField = result.get();
//获取用户输入的账号
String enteredAccount = idField.get(0).getText();
// 创建对话框,让用户输入工号
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("修改密码");
dialog.setHeaderText(null);
dialog.setContentText("请输入工号:");
// 等待用户输入工号
Optional<String> workIdResult = dialog.showAndWait();
if (workIdResult.isPresent()) {
// 获取用户输入的工号
String enteredWorkId = workIdResult.get();
// 获取数据库中的工号
String storedWorkId = getWorkIdByAccount(enteredAccount);
if (storedWorkId != null) {
if (storedWorkId.equals(enteredWorkId)) {
// 创建表单布局
GridPane formGrid = new GridPane();
formGrid.setHgap(10);
formGrid.setVgap(10);
// 定义表单字段和标签的名称
ArrayList<String> fieldLabels = new ArrayList<>(Arrays.asList("新密码", "确认新密码"));
ArrayList<TextField> fields = new ArrayList<>();
// 使用循环创建表单字段和标签
for (int i = 0; i < fieldLabels.size(); i++) {
TextField field = new TextField();
Label label = new Label(fieldLabels.get(i));
formGrid.add(label, 0, i);
formGrid.add(field, 1, i);
fields.add(field);
}
// 显示对话框,并等待用户点击按钮
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("修改密码");
alert.setHeaderText(null);
alert.getDialogPane().setContent(formGrid);
Optional<ButtonType> buttonResult = alert.showAndWait();
if (buttonResult.isPresent() && buttonResult.get() == ButtonType.OK) {
// 检查两次输入的密码是否一致
if (fields.get(0).getText().equals(fields.get(1).getText())) {
String newPassword = fields.get(0).getText();
// 调用数据库操作类的方法更新密码
connect.updatePassWord(enteredAccount, newPassword);
//刷新界面
showTeacherScene(enteredWorkId);
}
}
} else {
// 工号不匹配,提示错误信息
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("输入的工号与账号不匹配!");
alert.showAndWait();
}
} else {
// 账号不存在,提示错误信息
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("输入的账号不存在!");
alert.showAndWait();
}
}
}
}
//管理员界面
public void showAdminScene() {
// 清空之前的界面内容
borderPane.getChildren().clear();
try (Connection conn = connect.getConnection();
Statement stmt = conn.createStatement()) {
// 从teacher表中查询教师信息
String sql = "SELECT * FROM teacherinformation";
ResultSet rs = stmt.executeQuery(sql);
// 获取列数,将获取到的列放到结果集中
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 创建表格
TableView<ObservableList<String>> table = new TableView<>();
// 添加表头,根据获取到的列,添加表头
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
/*
ObservableList<String> 是每一行数据的类型,表示一行数据是一个字符串列表。
String 是单元格中数据的类型,表示每个单元格中的数据是字符串类型。
*/
TableColumn<ObservableList<String>, String> column = new TableColumn<>(columnName);
// 设置表头内容居中,并设置内容只读
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(table.getColumns().indexOf(column))));
table.getColumns().add(column);
}
// 添加数据行
while (rs.next()) {
ObservableList<String> data = FXCollections.observableArrayList();
for (int i = 1; i <= columnCount; i++) {
String cellValue = rs.getString(i);
data.add(cellValue);
}
table.getItems().add(data);
}
// 创建ScrollPane并将表格放入其中
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(table);
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
// 添加ScrollPane到布局中
borderPane.setCenter(scrollPane);
// 创建菜单
Menu fileMenu = new Menu("File");
Menu addMenu = new Menu("Add");
Menu deleteMenu = new Menu("Delete");
Menu editMenu = new Menu("Edit");
Menu searchMenu = new Menu("Search");
Menu setMenu = new Menu("Settings");
// 创建菜单项
MenuItem addTeacherItem = new MenuItem("Add Teacher");
MenuItem editTeacherItem = new MenuItem("Edit Teacher");
MenuItem deleteTeacherItem = new MenuItem("Delete Teacher");
MenuItem searchTeacherItem = new MenuItem("Search Teacher");
MenuItem logoutItem = new MenuItem("Log Out");
// 为菜单项添加事件处理程序
addTeacherItem.setOnAction(e -> addTeacher());
editTeacherItem.setOnAction(e -> amend());
deleteTeacherItem.setOnAction(e -> deleteTeacher());
searchTeacherItem.setOnAction(e -> searchTeacher());
logoutItem.setOnAction(e -> logout());
// 将菜单项添加到菜单中
fileMenu.getItems().addAll(setMenu);
addMenu.getItems().addAll(addTeacherItem);
deleteMenu.getItems().addAll(deleteTeacherItem);
editMenu.getItems().addAll(editTeacherItem);
searchMenu.getItems().addAll(searchTeacherItem);
setMenu.getItems().addAll(logoutItem);
MenuBar menuBar = new MenuBar();
// 将菜单添加到菜单栏
menuBar.getMenus().addAll(fileMenu, addMenu,editMenu, deleteMenu, searchMenu);
// 将菜单栏添加到布局中
borderPane.setTop(menuBar);
} catch (SQLException e) {
e.printStackTrace();
// 异常处理
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("显示教师信息失败!");
alert.showAndWait();
}
}
private void logout() {
BorderPane borderPane = new BorderPane();
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("确认退出");
alert.setHeaderText(null);
alert.setContentText("确定要退出登录吗?");
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK) {
// 用户点击了确定按钮,执行退出登录操作
initializeLoginData();
borderPane.getChildren().clear();
Stage stage = new Stage();
start(stage);
}
}
private void initializeLoginData() {
// 重置登录界面的数据
accountField.clear();
passwordField.clear();
}
private void searchTeacher() {
// 调用创建对话框的方法,并让用户输入要查询的教师工号
Optional<ArrayList<TextField>> result = createInputDialog("查询", "请输入要查询的教师工号");
if (result.isPresent()) {
// 用户点击了 "确定" 按钮,获取输入的工号
ArrayList<TextField> idField = result.get();
String workId = idField.get(0).getText();
// 根据工号从数据库中查询对应的教师信息
TeacherInformation teacher = queryById(workId);
if (teacher == null) {
// 如果没有查询到对应的教师信息,提示用户并返回
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText("未找到对应的教师信息");
alert.setContentText("请检查输入的工号是否正确!");
alert.showAndWait();
} else {
// 创建一个新的对话框,显示查询到的教师信息
Dialog<String> infoDialog = new Dialog<>();
infoDialog.setTitle("查询结果");
infoDialog.setHeaderText(null);
// 创建文本区域显示教师信息
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.appendText("姓名: " + teacher.getName() + "\n");
textArea.appendText("性别: " + teacher.getGender() + "\n");
textArea.appendText("年龄: " + teacher.getAge() + "\n");
textArea.appendText("工号: " + teacher.getWorkid() + "\n");
textArea.appendText("职称: " + teacher.getPosition() + "\n");
textArea.appendText("工作时间: " + teacher.getWorktime() + "\n");
// 将文本区域添加到对话框中
infoDialog.getDialogPane().setContent(textArea);
// 添加 "确定" 按钮
infoDialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
// 显示对话框并等待用户响应
infoDialog.showAndWait();
}
}
}
//删除教师
private void deleteTeacher() {
// 调用创建对话框的方法,并让用户输入要删除的教师工号
Optional<ArrayList<TextField>> result = createInputDialog("删除", "请输入要删除的教师工号");
if (result.isPresent()) {
// 用户点击了 "确定" 按钮,获取输入的工号
ArrayList<TextField> idField = result.get();
String workId = idField.get(0).getText();
// 根据工号从数据库中查询对应的教师信息
TeacherInformation teacher = queryById(workId);
if (teacher == null) {
// 如果没有查询到对应的教师信息,提示用户并返回
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText("未找到对应的教师信息");
alert.setContentText("请检查输入的工号是否正确!");
alert.showAndWait();
} else {
// 执行删除操作
if (connect.deleteTeacherById(workId)) {
// 删除成功,提示用户
Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
successAlert.setTitle("删除成功");
successAlert.setHeaderText(null);
successAlert.setContentText("教师信息删除成功!");
successAlert.showAndWait();
// 刷新界面
showAdminScene();
} else {
// 删除失败,提示用户
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setTitle("删除失败");
errorAlert.setHeaderText(null);
errorAlert.setContentText("教师信息删除失败!");
errorAlert.showAndWait();
}
}
}
}
private void addTeacher() {
// 创建一个对话框窗口
Dialog<ArrayList<Control>> dialog = new Dialog<>();
dialog.setTitle("添加教师");
dialog.setHeaderText(null);
// 设置对话框的按钮
ButtonType addButton = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButton = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(addButton, cancelButton);
// 创建表单布局
GridPane formGrid = new GridPane();
formGrid.setHgap(10);
formGrid.setVgap(10);
formGrid.setPadding(new Insets(20));
// 创建表单字段和标签
ArrayList<Control> controls = new ArrayList<>();
ArrayList<String> labels = new ArrayList<>(Arrays.asList("姓名:", "性别:", "年龄:", "工号:", "职位:", "所属学院:", "工作时间:"));
for (int i = 0; i < labels.size(); i++) {
Label label = new Label(labels.get(i));
formGrid.add(label, 0, i);
if(i == 5){
ComboBox<String> collegeComboBox = new ComboBox<>();
collegeComboBox.getItems().addAll(
"法学院(法律事务中心)",
"信息工程学院",
"水利学院",
"地球科学与工程学院(地球物理研究所)",
"测绘与地理信息学院",
"材料学院",
"土木与交通学院(钢结构与工程研究院)",
"电气工程学院",
"能源与动力工程学院",
"机械学院",
"环境与市政工程学院",
"水资源学院(黄河科学研究院)",
"管理与经济学院(MBA教育中心)",
"数学与统计学院",
"建筑学院",
"电子工程学院",
"外国语学院",
"公共管理学院(MPA教育中心)",
"国际教育学院(语言培训中心)",
"马克思主义学院",
"艺术学院",
"乌拉尔学院",
"体育教学部"
);
controls.add(collegeComboBox);
formGrid.add(collegeComboBox, 1, i);
} else {
TextField field = new TextField();
formGrid.add(field, 1, i);
controls.add(field);
// 为年龄和工号文本框添加事件监听器,设置正则表达式
if (i == 2 || i == 3) {
field.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) {
field.setText(oldValue);
}
});
}
}
}
// 将表单布局设置为对话框的内容
dialog.getDialogPane().setContent(formGrid);
// 设置对话框的结果转换器
dialog.setResultConverter(dialogButton -> {
if (dialogButton == addButton) {
// 点击添加按钮时,将输入的教师信息返回
return controls;
}
return null;
});
// 显示对话框并等待用户操作
Optional<ArrayList<Control>> result = dialog.showAndWait();
// 处理用户操作结果
result.ifPresent(inputs -> {
// 获取用户输入的教师信息
String name = ((TextField) inputs.get(0)).getText();
String gender = ((TextField) inputs.get(1)).getText();
int age = Integer.parseInt(((TextField) inputs.get(2)).getText());
String workid = ((TextField) inputs.get(3)).getText();
String position = ((TextField) inputs.get(4)).getText();
String college = ((ComboBox<String>) inputs.get(5)).getValue();
String worktime = ((TextField) inputs.get(6)).getText();
// 将教师信息插入到数据库中
try {
connect.insertTeacher(name, gender, age, workid, position, college, worktime);
// 插入成功后,刷新主界面
showAdminScene();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
//创建对话框
private GridPane createTeacherForm() {
// 创建表单布局
GridPane formGrid = new GridPane();
formGrid.setHgap(10);
formGrid.setVgap(10);
// 定义表单字段和标签的名称
ArrayList<String> fieldLabels = new ArrayList<>(Arrays.asList("姓名:", "性别:", "年龄:", "职位:", "所属学院:", "工作时间:"));
ArrayList<TextField> fields = new ArrayList<>();
// 使用循环创建表单字段和标签
for (int i = 0; i < fieldLabels.size(); i++) {
TextField field = new TextField();
Label label = new Label(fieldLabels.get(i));
formGrid.add(label, 0, i);
formGrid.add(field, 1, i);
fields.add(field);
}
return formGrid;
}
//修改教师信息
private void amend() {
// 调用创建对话框的方法,并让用户输入要查询的教师工号
Optional<ArrayList<TextField>> result = createInputDialog("修改", "请输入要修改的教师工号");
if(result.isPresent()) {
// 用户点击了 "确定" 按钮,获取输入的工号
ArrayList<TextField> idField = result.get();
String workId = idField.get(0).getText();
// 使用正则表达式限制工号只能输入数字
if (!workId.matches("\\d+")) {
// 如果工号不符合要求,提示用户并返回
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("请输入正确的教师工号!");
alert.showAndWait();
return;
}
// 根据工号从数据库中查询对应的教师信息
TeacherInformation teacher = queryById(workId);
if(teacher == null) {
// 如果没有查询到对应的教师信息,提示用户并返回
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText("未找到对应的教师信息");
alert.setContentText("请检查输入的工号是否正确!");
alert.showAndWait();
} else {
// 创建一个对话框窗口
Dialog<ArrayList<TextField>> dialog1 = new Dialog<>();
dialog1.setTitle("修改教师岗位信息");
dialog1.setHeaderText(null);
// 设置对话框的按钮
ButtonType addButton = new ButtonType("修改" , ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButton = new ButtonType("取消" , ButtonBar.ButtonData.CANCEL_CLOSE);
dialog1.getDialogPane().getButtonTypes().addAll(addButton , cancelButton);
// 创建表单布局并获取字段对象
GridPane formGrid = createTeacherForm();
ArrayList<TextField> fields = new ArrayList<>(formGrid.getChildren().size());
for(Node node : formGrid.getChildren()) {
if(node instanceof TextField) {
fields.add((TextField) node);
}
}
// 在addTeacher和amend方法中创建下拉列表,设置可选项并添加到表单布局中
ComboBox<String> collegeComboBox = new ComboBox<>();
collegeComboBox.getItems().addAll(
"法学院(法律事务中心)",
"信息工程学院",
"水利学院",
"地球科学与工程学院(地球物理研究所)",
"测绘与地理信息学院",
"材料学院",
"土木与交通学院(钢结构与工程研究院)",
"电气工程学院",
"能源与动力工程学院",
"机械学院",
"环境与市政工程学院",
"水资源学院(黄河科学研究院)",
"管理与经济学院(MBA教育中心)",
"数学与统计学院",
"建筑学院",
"电子工程学院",
"外国语学院",
"公共管理学院(MPA教育中心)",
"国际教育学院(语言培训中心)",
"马克思主义学院",
"艺术学院",
"乌拉尔学院",
"体育教学部"
);
formGrid.add(collegeComboBox, 1, 4);
// 使用正则表达式限制年龄只能输入数字
TextField ageField = fields.get(2);
ageField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) {
ageField.setText(newValue.replaceAll("[^\\d]", ""));
}
});
// 设置对话框的结果转换器
dialog1.setResultConverter(dialogButton -> {
if(dialogButton == addButton) {
// 点击添加按钮时,将输入的教师信息返回
return fields;
}
return null;
});
// 将表单布局设置为对话框的内容
dialog1.getDialogPane().setContent(formGrid);
// 显示对话框并等待用户操作
Optional<ArrayList<TextField>> result1 = dialog1.showAndWait();
// 处理用户操作结果
result1.ifPresent(inputs -> {
// 获取用户输入的教师信息
String name = inputs.get(0).getText();
String gender = inputs.get(1).getText();
int age = Integer.parseInt(inputs.get(2).getText());
String position = inputs.get(3).getText();
String college = collegeComboBox.getValue();
String worktime = inputs.get(5).getText();
// 将教师信息插入到数据库中
connect.updateTeacher(name, gender, age ,workId , position, college, worktime);
System.out.println("UPDATE teacherinformation SET name='" + name + "', gender='" + gender + "', age=" + age + ", position='" + position + "', worktime='" + worktime + "', college='" + college + "' WHERE workid='" + workId + "'");
// 刷新教师列表
showAdminScene();
});
}
}
}
//根据工号查询数据库中是否有对应的教师信息
public TeacherInformation queryById(String workId) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
TeacherInformation teacher = null;
try {
// 获取数据库连接
conn = connect.getConnection();
// 创建 PreparedStatement 对象,并设置占位符参数
String sql = "SELECT * FROM teacherinformation WHERE workid=?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, workId);
// 执行查询操作
rs = stmt.executeQuery();
// 处理结果集,将查询到的教师信息保存到一个 Teacher 对象中
if (rs.next()) {
String name = rs.getString("name");
String gender = rs.getString("gender");
int age = rs.getInt("age");
String position = rs.getString("position");
String worktime = rs.getString("worktime");
String college = rs.getString("college");
teacher = new TeacherInformation(name, gender, age, workId, position,worktime,college);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接,语句和结果集
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return teacher;
}
public void register() {
// 创建表单布局
GridPane formGrid = new GridPane();
formGrid.setHgap(10);
formGrid.setVgap(10);
// 定义表单字段和标签的名称
ArrayList<String> fieldLabels = new ArrayList<>(Arrays.asList("账户", "密码", "工号"));
ArrayList<TextField> fields = new ArrayList<>();
// 使用循环创建表单字段和标签
for (int i = 0; i < fieldLabels.size(); i++) {
TextField field = new TextField();
Label label = new Label(fieldLabels.get(i));
formGrid.add(label, 0, i);
formGrid.add(field, 1, i);
fields.add(field);
// 添加事件监听器,验证输入的内容是否符合要求
if (i == 0 || i == 1) {
field.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("[a-zA-Z0-9]*")) {
field.setText(oldValue);
}
});
}
else {
field.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("[0-9]*")) {
field.setText(oldValue);
}
});
}
}
// 显示对话框,并等待用户点击按钮
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("注册账户");
dialog.getDialogPane().setContent(formGrid);
// 添加OK和Cancel按钮
ButtonType okButton = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButton = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okButton, cancelButton);
// 等待用户点击按钮并获取结果
Optional<ButtonType> result = dialog.showAndWait();
if (result.isPresent() && result.get() == okButton) {
String account = fields.get(0).getText();
String password = fields.get(1).getText();
String workId = fields.get(2).getText();
// 检查用户名是否已存在
if (checkNameExist(account)) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("用户名已存在!");
alert.showAndWait();
return;
}
// 注册新用户
if (createTeacherAccount(account, password, workId)) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("注册成功!");
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("注册失败!");
alert.showAndWait();
}
}
}
//将创建的新用户添加到数据库中
public boolean createTeacherAccount(String account, String password,String workId) {
String sql = "INSERT INTO teacher (account, password, workid) VALUES (?, ? ,?)";
try (Connection conn = connect.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, account);
stmt.setString(2, password);
stmt.setString(3, workId);
int result = stmt.executeUpdate();
return result > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private boolean checkNameExist(String name) {
boolean result = false;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = connect.getConnection();
// 执行查询语句
String sql = "SELECT account FROM teacher";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 判断是否有和name相同的值
while (rs.next()) {
String account = rs.getString("account");
if (account.equals(name)) {
result = true;
break;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
//创建一个对话框
public Optional<ArrayList<TextField>> createInputDialog(String title, String headerText) {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle(title);
dialog.setHeaderText(headerText);
// 创建工号输入框并添加到对话框中
TextField workIdField = new TextField();
dialog.getDialogPane().setContent(workIdField);
// 创建 "确定" 和 "取消" 按钮并添加到对话框中
ButtonType confirmButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL);
// 设置按钮的可用性
Node confirmButton = dialog.getDialogPane().lookupButton(confirmButtonType);
confirmButton.setDisable(true);
workIdField.textProperty().addListener((observable, oldValue, newValue) -> {
confirmButton.setDisable(newValue.trim().isEmpty());
});
// 显示对话框并等待用户响应
Optional<ButtonType> result = dialog.showAndWait();
if (result.isPresent() && result.get() == confirmButtonType) {
ArrayList<TextField> fields = new ArrayList<>();
fields.add(workIdField);
return Optional.of(fields);
} else {
return Optional.empty();
}
}
public static void main(String[] args) {
launch();
}
}
根据上述代码,帮我写以上系统的详细描述。
要求:总结设计用到的主要工具,详细介绍一下整个系统的主要功能模块。 |
|