Java+Swing: 数据回显和修改功能的实现 整理14

2023-12-18 22:12:23

1. 数据回显

其实数据回显就是为修改功能的实现做准备的

1.1 在MainView类中,创建一个方法获取选中行的id?

    // 获取选中的行的id
    public int[] getSelectedRowIds() {
        int[] selectedRows = mainViewTable.getSelectedRows();
        int[] ids = new int[selectedRows.length];  // 用来存储id

        for (int i = 0; i < selectedRows.length; i++) {
            int selectedRowIndex = selectedRows[i];
            Object idObj = mainViewTable.getValueAt(selectedRowIndex, 0);
            ids[i]= Integer.parseInt(idObj.toString()); // toString()是将转为字符串的类型
        }
        return ids;
    }

1.2 给按钮添加点击事件

?

1.3 在MainViewHandler进行相应的处理

 if ("修改".equals(text)){
     int[] selectedRowIds = mainView.getSelectedRowIds();
     if (selectedRowIds.length != 1) {
           JOptionPane.showMessageDialog(mainView, "请选择一条记录!");
           return;
     }
     new UpdateStudentView(mainView, selectedRowIds[0]);
 }

?

1.4 编写UpdateStudentView界面代码

与上一篇博客中的添加数据界面相同,直接给出代码了

package com.student_view;

import com.entity.Student;
import com.handler.UpdateStudentViewHandler;
import com.service.Impl.StudentServiceImpl;

import javax.swing.*;
import java.awt.*;

/**
 * @Author:xiexu
 * @Date:2023/12/16 21:52
 */
public class UpdateStudentView extends JDialog {
    // 声明一系列组件
    JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 20));
    JLabel idLabel = new JLabel("学号", JLabel.RIGHT);
    JTextField idTextField = new JTextField();
    JLabel nameLabel = new JLabel("姓名", JLabel.RIGHT); // 第二个参数表示水平的排列方式
    JTextField nameTextField = new JTextField();
    JLabel noLabel = new JLabel("学号", JLabel.RIGHT);
    JTextField noTextField = new JTextField();
    JLabel homeLabel =  new JLabel("家乡", JLabel.RIGHT);
    JTextField homeTextField = new JTextField();
    JLabel chineseLabel = new JLabel("语文成绩", JLabel.RIGHT);
    JTextField chineseTextField = new JTextField();
    JLabel mathLabel = new JLabel("数学成绩", JLabel.RIGHT);
    JTextField mathTextField = new JTextField();
    JLabel englishLabel = new JLabel("英语成绩", JLabel.RIGHT);
    JTextField englishTextField = new JTextField();
    JButton updateBtn = new JButton("修改");

    public UpdateStudentView(MainView mainView, int selectedRowId) {
        super(mainView, "修改学生信息",true);

        // 添加各组件到面板上
        idLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(idLabel);
        idTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(idTextField);


        nameLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(nameLabel);
        nameTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(nameTextField);

        noLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(noLabel);
        noTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(noTextField);

        homeLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(homeLabel);
        homeTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(homeTextField);

        chineseLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(chineseLabel);
        chineseTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(chineseTextField);

        mathLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(mathLabel);
        mathTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(mathTextField);

        englishLabel.setPreferredSize(new Dimension(80, 30));
        jPanel.add(englishLabel);
        englishTextField.setPreferredSize(new Dimension(200, 30));
        jPanel.add(englishTextField);

        jPanel.add(updateBtn);

        Container contentPane = getContentPane();
        contentPane.add(jPanel);

        setSize(350, 500);
        setLocationRelativeTo(null);
        // DISPOSE_ON_CLOSE  只销毁当前窗体
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }

}

?

1.5 实现数据回显

就是根据传过来的id值,查询数据库,在展示到对应的表单中

1.5.1 接口?

Student getById(int selectedRowId);

1.5.2 实现类?

    // 根据 id 查询
    @Override
    public Student getById(int selectedRowId) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from detail where id = ?");
        // 执行
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        Student student = new Student();// 返回的数据
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1, selectedRowId);
            resultSet = preparedStatement.executeQuery();  // 执行查询返回结果集

            while (resultSet.next()) {
                // 遍历查询的每一条记录
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String no = resultSet.getString("no");
                String homeTown = resultSet.getString("homeTown");
                double chinese = resultSet.getDouble("chinese");
                double math = resultSet.getDouble("math");
                double english = resultSet.getDouble("english");
                student.setId(id);
                student.setName(name);
                student.setNo(no);
                student.setHomeTown(homeTown);
                student.setChinese(chinese);
                student.setMath(math);
                student.setEnglish(english);
            }
            return student;
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeRS(resultSet);
            DBUtil.closePS(preparedStatement);
            DBUtil.closeConnection(connection);
        }

        return null;
    }

?1.5.3 在updateStudentView中对返回的结果进行相应的处理

   // 查询selectedRowIds对应的数据并回显
   StudentServiceImpl studentService = new StudentServiceImpl();
   Student selectedStudent = studentService.getById(selectedRowId);

把返回的结果设置到相应的表单中,注意id需设为不可编辑 ,这里只给出了部分,其他的组件也是一样的写法

?

1.5.4 效果

?

?2. 修改数据

在上面的基础上,对修改数据的模态框进行处理

2.1 给模态框中的修改按钮添加点击事件

?

2.2 编写事件处理类updateStudentViewHandler

以下代码中给出了框架,具体的逻辑还没实现,具体的实现继续往下看

package com.handler;

import com.entity.Student;
import com.service.Impl.StudentServiceImpl;
import com.student_view.MainView;
import com.student_view.UpdateStudentView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @Author:xiexu
 * @Date:2023/12/18 17:33
 */
public class UpdateStudentViewHandler implements ActionListener {
    private UpdateStudentView updateStudentView;
    private MainView mainView;

    public UpdateStudentViewHandler(UpdateStudentView updateStudentView, MainView mainView) {
        this.updateStudentView = updateStudentView;
        this.mainView = mainView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();

        if ("修改".equals(text)) {
            .......

            if (...) {
                // 重新加载表格查到最新数据
                mainView.reloadTable();
                updateStudentView.dispose();

            } else {
                // 添加错误,给出提示
                JOptionPane.showMessageDialog(updateStudentView, "添加失败");
            }
        }
    }
}

2.3 在updateStudentView中实例化

需要传递两个参数,这边将mainView传过去,是便于修改数据成功后,调用reloadTable方法,重新加载表格。

    UpdateStudentViewHandler updateStudentViewHandler;


    updateStudentViewHandler = new UpdateStudentViewHandler(this, mainView);

?

2.4 实现数据的修改操作逻辑

2.4.1 接口

 boolean update(Student student);

2.4.2 实现类

    // 修改/更新
    @Override
    public boolean update(Student student) {
        StringBuilder sql = new StringBuilder();
        sql.append("update detail set name=?, no=?, homeTown=?, chinese=?, math=?, english=?");
        sql.append("where id = ?");

        // 执行
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        TableDTO tableDTO = new TableDTO(); // 返回的数据
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setString(1, student.getName());
            preparedStatement.setString(2, student.getNo());
            preparedStatement.setString(3, student.getHomeTown());
            preparedStatement.setDouble(4, student.getChinese());
            preparedStatement.setDouble(5, student.getMath());
            preparedStatement.setDouble(6, student.getEnglish());
            preparedStatement.setInt(7,student.getId());

            return preparedStatement.executeUpdate() == 1;  // 执行查询返回结果集
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeRS(resultSet);
            DBUtil.closePS(preparedStatement);
            DBUtil.closeConnection(connection);
        }

        return false;
    }

2.4.3 补全上述的代码

?

?2.4.4 上述也是需要一个方法将属性值封装成一个对象

 public Student builStudent() {
        Student student = new Student();
        student.setId(Integer.valueOf(idTextField.getText()));
        student.setName(nameTextField.getText());
        student.setNo(noTextField.getText());
        student.setHomeTown(homeTextField.getText());
        student.setChinese(Double.parseDouble(chineseTextField.getText()));
        student.setMath(Double.parseDouble(mathTextField.getText()));
        student.setEnglish(Double.parseDouble(englishTextField.getText()));
        return student;
 }

?

?

文章来源:https://blog.csdn.net/m0_61495539/article/details/135070039
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。