java
@FishC下面使我完整的代码,在调用addTeacher方法是会出现这个错误
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.beans.property.StringProperty.set(Object)" because "this.name" is null
package com.example.javafxmw;
import TeacherPostsSystem.TeacherInformation;
import javafx.application.Application;
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.Optional;
public class HelloApplicationextends Application{
public TextField accountField = new TextField();
public PasswordField passwordField = new PasswordField();
ToggleGroup toggleGroup = new ToggleGroup();
RadioButton adminRadioButton = new RadioButton("管理员");
BorderPane borderPane = new BorderPane();
TableView<TeacherInformation> teacherTableView = new TableView<>();
ObservableList<TeacherInformation> teacherList = FXCollections.observableArrayList();
TextField infoTextField = new TextField();
@Override
public void start(Stage stage) {
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(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
// 登录功能
login();
}
});
// 创建注册按钮
Button registerButton = new Button("注册");
registerButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
// 注册功能,管理员账号写死,不可注册和修改,教师账号可注册
register();
}
});
// 创建单选按钮
adminRadioButton.setToggleGroup(toggleGroup);
adminRadioButton.setSelected(true); // 默认选中管理员登录
RadioButton teacherRadioButton = new RadioButton("教师");
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();
}
// 数据库连接
private Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/teacherportsystem";
String username = "root";
String password = "1542";
return DriverManager.getConnection(url , username , password);
}
//登录方法
public void login() {
String account = accountField.getText();
String password = passwordField.getText();
// 判断选择的身份
boolean isAdmin = toggleGroup.getSelectedToggle().equals(adminRadioButton);
String tableName = isAdmin ? "admin" : "teacher";
// 从对应的表中查询账号和密码
String sql = "SELECT * FROM " + tableName + " WHERE account = ?";
try (Connection conn = 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();
// 展示新的界面
showMainScene();
} 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 void showMainScene() {
// 创建表格
TableColumn<TeacherInformation, String> nameColumn = new TableColumn<>("姓名");
TableColumn<TeacherInformation, String> ageColumn = new TableColumn<>("年龄");
TableColumn<TeacherInformation, String> sexColumn = new TableColumn<>("性别");
TableColumn<TeacherInformation, String> wordIdColumn = new TableColumn<>("工号");
TableColumn<TeacherInformation, String> portColumn = new TableColumn<>("职称");
// 设置列宽
nameColumn.setPrefWidth(80);
ageColumn.setPrefWidth(60);
sexColumn.setPrefWidth(60);
wordIdColumn.setPrefWidth(120);
portColumn.setPrefWidth(80);
// 绑定列和属性
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
ageColumn.setCellValueFactory(cellData -> cellData.getValue().ageProperty());
sexColumn.setCellValueFactory(cellData -> cellData.getValue().sexProperty());
wordIdColumn.setCellValueFactory(cellData -> cellData.getValue().wordIdProperty());
portColumn.setCellValueFactory(cellData -> cellData.getValue().portProperty());
// 将列添加到表格中
teacherTableView.getColumns().addAll(nameColumn, ageColumn, sexColumn, wordIdColumn, portColumn);
// 从数据库中读取教师信息
try (Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM teacherinformation")) {
while (rs.next()) {
String name = rs.getString("name");
String age = rs.getString("age");
String sex = rs.getString("sex");
String workId = rs.getString("workid");
String port = rs.getString("port");
TeacherInformation teacher = new TeacherInformation(name, age, sex, workId, port);
teacherList.add(teacher);
}
} catch (SQLException e) {
e.printStackTrace();
}
// 将教师信息添加到表格中
teacherTableView.setItems(teacherList);
// 创建文本框显示从数据库中读取到的教师信息
infoTextField.setEditable(false);
infoTextField.setPromptText("从数据库中读取到的教师信息:");
infoTextField.setText("共读取到" + teacherList.size() + "条教师信息。");
// 创建增加的功能按钮
Button addButton = new Button("添加");
addButton.setOnAction(e -> addTeacher());
//查询
Button queryButton = new Button("查询");
queryButton.setOnAction(e -> queryTeacher());
//修改
Button modifyButton = new Button("修改");
modifyButton.setOnAction(e -> modifyTeacher());
//删除
Button deleteButton = new Button("删除");
deleteButton.setOnAction(e -> deleteTeacher());
// 将功能按钮添加到HBox中
HBox buttonBox = new HBox();
buttonBox.getChildren().addAll(addButton, queryButton, modifyButton, deleteButton);
buttonBox.setAlignment(Pos.CENTER);
buttonBox.setSpacing(10);
// 将文本框、表格和底部的功能按钮添加到VBox中
VBox vBox = new VBox();
vBox.getChildren().addAll(infoTextField, teacherTableView, buttonBox);
vBox.setAlignment(Pos.CENTER);
vBox.setSpacing(10);
Scene mainScene = new Scene(vBox, 800, 640);
Stage mainStage = new Stage();
mainStage.setTitle("教师岗位管理系统");
mainStage.setScene(mainScene);
mainStage.show();
}
private void deleteTeacher() {
}
private void modifyTeacher() {
}
private void queryTeacher() {
}
private void addTeacher() {
// 创建新增教师的Dialog
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("新增教师");
dialog.setHeaderText(null);
// 设置Dialog的按钮
ButtonType confirmButtonType = new ButtonType("确认", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL);
// 创建文本框和标签,用于输入教师的各项信息
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
Label nameLabel = new Label("姓名:");
TextField nameField = new TextField();
nameField.setPromptText("请输入教师姓名");
gridPane.add(nameLabel, 0, 0);
gridPane.add(nameField, 1, 0);
Label ageLabel = new Label("年龄:");
TextField ageField = new TextField();
ageField.setPromptText("请输入教师年龄");
gridPane.add(ageLabel, 0, 1);
gridPane.add(ageField, 1, 1);
Label sexLabel = new Label("性别:");
TextField sexField = new TextField();
sexField.setPromptText("请输入教师性别");
gridPane.add(sexLabel, 0, 2);
gridPane.add(sexField, 1, 2);
Label wordIdLabel = new Label("工号:");
TextField wordIdField = new TextField();
wordIdField.setPromptText("请输入教师工号");
gridPane.add(wordIdLabel, 0, 3);
gridPane.add(wordIdField, 1, 3);
Label portLabel = new Label("职称:");
TextField portField = new TextField();
portField.setPromptText("请输入教师职称");
gridPane.add(portLabel, 0, 4);
gridPane.add(portField, 1, 4);
// 将GridPane添加到Dialog的主体部分
dialog.getDialogPane().setContent(gridPane);
// 显示Dialog,并等待用户输入
Optional<ButtonType> result = dialog.showAndWait();
if (result.isPresent() && result.get().equals(confirmButtonType)) {
// 获取用户输入的教师信息
TeacherInformation teacher = new TeacherInformation();
teacher.setName(nameField.getText());
teacher.setAge(String.valueOf(Integer.parseInt(ageField.getText())));
teacher.setSex(sexField.getText());
teacher.setWordId(wordIdField.getText());
teacher.setPort(portField.getText());
// 检查工号是否已存在
for (TeacherInformation item : teacherTableView.getItems()) {
if (item.getWordId().equals(teacher.getWordId())) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("警告");
alert.setHeaderText(null);
alert.setContentText("工号已存在,请重新输入!");
alert.showAndWait();
return;
}
}
// 将教师信息添加到表格中
teacherTableView.getItems().add(teacher);
// 更新文本框的内容
infoTextField.setText("共读取到" + teacherTableView.getItems().size() + "条教师信息。");
}
}
public void register() {
String account = accountField.getText();
String password = passwordField.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)) {
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();
}
}
private boolean createTeacherAccount(String account, String password) {
String sql = "INSERT INTO teacher (account, password) VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, account);
stmt.setString(2, password);
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 = 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 static void main(String[] args) {
launch();
}
}
这个错误发生在调用addTeacher方法时出现了空指针异常。根据错误信息,是因为"this.name"为空,无法调用StringProperty的set方法。
你可以检查一下TeacherInformation类中的name属性是否已经正确使用StringProperty进行初始化。如果没有初始化,那么在调用set方法时就会出现空指针异常。
另外,如果你可以提供TeacherInformation类的源代码,我也可以更详细地帮你找出问题所在。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 FishC 发表于 2023-12-31 23:02
这个错误发生在调用addTeacher方法时出现了空指针异常。根据错误信息,是因为"this.name"为空,无法调用Str ...
@FishC
package TeacherPostsSystem;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class TeacherInformation {
private StringProperty name;
private StringProperty age;
private StringProperty sex;
private StringProperty workId;
private StringProperty port;
public TeacherInformation() {
}
public TeacherInformation(String name, String age, String sex, String workId, String port) {
this.name = new SimpleStringProperty(name);
this.age = new SimpleStringProperty(age);
this.sex = new SimpleStringProperty(sex);
this.workId = new SimpleStringProperty(workId);
this.port = new SimpleStringProperty(port);
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getAge() {
return age.get();
}
public StringProperty ageProperty() {
return age;
}
public void setAge(String age) {
this.age.set(age);
}
public String getSex() {
return sex.get();
}
public StringProperty sexProperty() {
return sex;
}
public void setSex(String sex) {
this.sex.set(sex);
}
public String getWordId() {
return workId.get();
}
public StringProperty wordIdProperty() {
return workId;
}
public void setWordId(String wordId) {
this.workId.set(wordId);
}
public String getPort() {
return port.get();
}
public StringProperty portProperty() {
return port;
}
public void setPort(String port) {
this.port.set(port);
}
}
这是我的teacherInformation类,我应该如何修改 就當我是浮誇吧 发表于 2023-12-31 23:03
@FishC
package TeacherPostsSystem;
import java ...
您的TeacherInformation类看起来已经定义得相当完整了。不过,如果你需要做一些修改的话,以下是一些建议:
1. 首先,你可以为每个属性添加一种可观察的属性类型,这样当属性发生变化时,您可以很容易地通知到其他部分:
private final StringProperty name;
private final StringProperty age;
private final StringProperty sex;
private final StringProperty workId;
private final StringProperty port;
2. 其次,你可以删除默认的无参构造方法,因为它目前没有起到任何作用。
3. 最后,你可以通过添加`toString()`方法,方便地将对象转换为字符串,以便打印或调试:
@Override
public String toString() {
return "Name: " + getName() +
", Age: " + getAge() +
", Sex: " + getSex() +
", Work ID: " + getWordId() +
", Port: " + getPort();
}
这些是一些简单的改进建议,希望对你有所帮助!如果你有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 FishC 发表于 2023-12-31 23:04
您的TeacherInformation类看起来已经定义得相当完整了。不过,如果你需要做一些修改的话,以下是一些建 ...
@FishC
既然你说没有问题为什么还会出现
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.beans.property.StringProperty.set(Object)" because "this.name" is null这个报错 就當我是浮誇吧 发表于 2023-12-31 23:06
@FishC
既然你说没有问题为什么还会出现
Exception...
哈哈,这个错误应该是你在使用JavaFX时出现的问题。NullPointerException(空指针异常)通常是因为你在使用一个空对象的方法或者属性。在这个错误信息中,我们可以看到是因为你调用了一个名叫"name"的StringProperty对象的set方法,但是这个对象为空。
造成这个错误的原因可能是你没有正确地初始化这个StringProperty对象。在JavaFX中,通常我们使用SimpleStringProperty来创建一个StringProperty对象。请确保你已经在正确的时机创建并初始化了这个对象,比如在构造函数中或者在其他需要的地方。
下面是一个简单的例子,演示了如何初始化StringProperty对象:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Example {
private StringProperty name; // 声明一个StringProperty对象
public Example() {
name = new SimpleStringProperty(); // 在构造函数中初始化StringProperty对象
}
public void setName(String newName) {
name.set(newName); // 使用set方法设置StringProperty的值
}
public String getName() {
return name.get(); // 使用get方法获取StringProperty的值
}
}
这样,在后续的代码中,你就可以使用setName()和getName()方法来设置和获取name属性的值了,而不会出现空指针异常啦。希望这个例子可以帮助你解决问题哦!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 <template>
<el-card class="page-container">
<template #header>
<div class="header">
<span>修改密码</span>
</div>
</template>
<el-row>
<el-col :span="12">
<el-form :model="passwordData" @submit.prevent="updatePassword" class="password-form" label-width="100px" size="large">
<el-form-item label="旧密码">
<el-input v-model="passwordData.old_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="新密码">
<el-input v-model="passwordData.new_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="确认新密码">
<el-input v-model="passwordData.re_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="updatePassword">修改密码</el-button>
</el-form-item>
</el-form>
</el-col>
</el-row>
</el-card>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { updateUserPasswordService } from '@/api/user';
import { useTokenStore } from '@/stores/token';
const router = useRouter();
const passwordData = ref({
old_pwd: '',
new_pwd: '',
re_pwd: ''
});
const tokenStore = useTokenStore();
const updatePassword = async () => {
if (passwordData.value.new_pwd !== passwordData.value.re_pwd) {
ElMessage.error('两次输入的密码不一致');
return;
}
try {
let result = await updateUserPasswordService(passwordData.value);
if (result.data && result.data.success) {
ElMessage.success(result.message ? result.message : '密码修改成功');
await tokenStore.removeToken();
router.push('/login');
} else {
ElMessage.error(result.message ? result.message : '密码修改失败');
}
} catch (error) {
ElMessage.error('密码修改失败:' + (error.message || '未知错误'));
}
};
</script>
<style scoped>
</style>
/**
* 修改用户密码
*/
export const updateUserPasswordService = (passwordData) => {
return request.patch('/user/updatePwd', passwordData)
}
import { defineStore } from "pinia";
import {ref} from 'vue';
/*
defineStore参数描述:
第一个参数:给状态起名,具有唯一性
第二个参数:函数,可以把定义该状态中拥有的内容
defineStore返回值描述:
返回的是一个函数,将来可以调用该函数,得到第二个参数中返回的内容
*/
export const useTokenStore = defineStore('token',()=>{
//1.定义描述token
const token = ref('')
//2.定义修改token的方法
const setToken = (newToken)=>{
token.value = newToken
}
//3.定义移除token的方法
const removeToken = ()=>{
token.value=''
}
return {
token,setToken,removeToken
}
},{
persistedState:true //持久化存储token
})
目前这个修改密码功能有问题,后端能够输出正确的数据库语句,能正常修改密码
但是前端没有跳转到正确的页面,也没有显示正确的elemessage消息 阿斯达 <template>
<el-card class="page-container">
<template #header>
<div class="header">
<span>修改密码</span>
</div>
</template>
<el-row>
<el-col :span="12">
<el-form :model="passwordData" @submit.prevent="updatePassword" class="password-form" label-width="100px" size="large">
<el-form-item label="旧密码">
<el-input v-model="passwordData.old_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="新密码">
<el-input v-model="passwordData.new_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="确认新密码">
<el-input v-model="passwordData.re_pwd" type="password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="updatePassword">修改密码</el-button>
</el-form-item>
</el-form>
</el-col>
</el-row>
</el-card>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { updateUserPasswordService } from '@/api/user';
import { useTokenStore } from '@/stores/token';
const router = useRouter();
const passwordData = ref({
old_pwd: '',
new_pwd: '',
re_pwd: ''
});
const tokenStore = useTokenStore();
const updatePassword = async () => {
if (passwordData.value.new_pwd !== passwordData.value.re_pwd) {
ElMessage.error('两次输入的密码不一致');
return;
}
try {
let result = await updateUserPasswordService(passwordData.value);
if (result.data && result.data.success) {
ElMessage.success(result.message ? result.message : '密码修改成功');
await tokenStore.removeToken();
router.push('/login');
} else {
ElMessage.error(result.message ? result.message : '密码修改失败');
}
} catch (error) {
ElMessage.error('密码修改失败:' + (error.message || '未知错误'));
}
};
</script>
<style scoped>
</style>
/**
* 修改用户密码
*/
export const updateUserPasswordService = (passwordData) => {
return request.patch('/user/updatePwd', passwordData)
}
import { defineStore } from "pinia";
import {ref} from 'vue';
/*
defineStore参数描述:
第一个参数:给状态起名,具有唯一性
第二个参数:函数,可以把定义该状态中拥有的内容
defineStore返回值描述:
返回的是一个函数,将来可以调用该函数,得到第二个参数中返回的内容
*/
export const useTokenStore = defineStore('token',()=>{
//1.定义描述token
const token = ref('')
//2.定义修改token的方法
const setToken = (newToken)=>{
token.value = newToken
}
//3.定义移除token的方法
const removeToken = ()=>{
token.value=''
}
return {
token,setToken,removeToken
}
},{
persistedState:true //持久化存储token
})
目前这个修改密码功能有问题,后端能够输出正确的数据库语句,能正常修改密码
但是前端没有跳转到正确的页面,也没有显示正确的elemessage消息
页:
[1]