当前位置: 首页 > 知识库问答 >
问题:

为什么JTable数据在编辑后不会改变?

陈松
2023-03-14

我可以从数据库中获取数据并将其存储在JTable中。所有工作都很好,但是如果我从表中编辑数据并按enter键,数据就不会编辑。

值更改后不会在表中重写。

构造函数和getter/setter

public class employee {
    private Integer emp_code;
    private String f_name;
    private String l_name;
    private Integer age;
    private String birth;
    private String nationality;
    private String gender;
    private String contact;
    private String contact2;
    private String address;
    private Integer gov_id;
    private String passport_no;
    private String profile;

    public employee(Integer emp_code, String f_name, String l_name, Integer age, String birth, String nationality, String gender, String contact, String contact2, String address, Integer gov_id, String passport_no, String profile) {
        this.emp_code = emp_code;
        this.f_name = f_name;
        this.l_name = l_name;
        this.age = age;
        this.birth = birth;
        this.nationality = nationality;
        this.gender = gender;
        this.contact = contact;
        this.contact2 = contact2;
        this.address = address;
        this.gov_id = gov_id;
        this.passport_no = passport_no;
        this.profile = profile;
    }

    // getter setter

}
public class TheModel extends AbstractTableModel {

    private String[] columns;
    private Object[][] rows;
    private boolean[] edit;

    public TheModel() {
    }

    public TheModel(Object[][] data, String[] columnName, boolean[] canEdit) {
        this.rows = data;
        this.columns = columnName;
        this.edit = canEdit;
    }

    public Class getColumnClass(int column) {
        if (column == 12) {
            return Icon.class;
        } else {
            return getValueAt(0, column).getClass();
        }
    }

    public int getRowCount() {
        return this.rows.length;
    }

    public int getColumnCount() {
        return this.columns.length;

    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return this.rows[rowIndex][columnIndex];
    }

    public String getColumnName(int col) {
        return this.columns[col];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return edit[columnIndex];
    }

}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        getEmployee();
      } 

public void getEmployee() {

        ArrayList<employee> list = getTable();
        String[] columnName = {"Code", "f_name", "l_name", "Age", "Birth", "Nationality", "Gender", "Contact", "Contact2", "Address", "Gov. id", "Passport no", "Profile"};
        boolean[] canEdit = new boolean[]{
            false, false, false, false, false, false, false, false, false, false, false, false, false
        };
        Object[][] rows = new Object[list.size()][13];
        for (int i = 0; i < list.size(); i++) {
            rows[i][0] = list.get(i).getEmp_code();
            rows[i][1] = list.get(i).getF_name();
            rows[i][2] = list.get(i).getL_name();
            rows[i][3] = list.get(i).getAge();
            rows[i][4] = list.get(i).getBirth();
            rows[i][5] = list.get(i).getNationality();
            rows[i][6] = list.get(i).getGender();
            rows[i][7] = list.get(i).getContact();
            rows[i][8] = list.get(i).getContact2();
            rows[i][9] = list.get(i).getAddress();
            rows[i][10] = list.get(i).getGov_id();
            rows[i][11] = list.get(i).getPassport_no();
            if (list.get(i).getProfile() != "") {
                ImageIcon MyImage = new ImageIcon(new ImageIcon(list.get(i).getProfile()).getImage()
                        .getScaledInstance(70, 50, Image.SCALE_SMOOTH));

                rows[i][12] = MyImage;
            } else {
                rows[i][12] = null;
            }

        }

        TheModel model = new TheModel(rows, columnName, canEdit);
        model.fireTableDataChanged();
        jTable1.setModel(model);
        jTable1.setRowHeight(50);
        jTable1.getColumnModel().getColumn(12).setPreferredWidth(70);
    }

    public ArrayList<employee> getTable() {
        ArrayList<employee> list = new ArrayList<employee>();
        PreparedStatement pst;
        ResultSet r;
        try {
            Connection cn = null;
            Class.forName("com.mysql.jdbc.Driver");
            cn = DriverManager.getConnection("jdbc:mysql://localhost/car_inventory_system", "root", "");
            pst = cn.prepareStatement("SELECT * FROM employee_registration_master WHERE f_name = ? OR l_name = ?");
            pst.setString(1, txtSearch.getText());
            pst.setString(2, txtSearch.getText());
            r = pst.executeQuery();
            employee e;
            while (r.next()) {
                e = new employee(
                        r.getInt("emp_code"),
                        r.getString("f_name"),
                        r.getString("l_name"),
                        r.getInt("age"),
                        r.getString("birth"),
                        r.getString("nationality"),
                        r.getString("gender"),
                        r.getString("contact"),
                        r.getString("contact2"),
                        r.getString("address"),
                        r.getInt("gov_id"),
                        r.getString("passport_no"),
                        r.getString("profile")
                );
                list.add(e);
            }
            pst.close();
            cn.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return list;
    }

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        //populateJTable();
        PreparedStatement pst;
        ResultSet r;
        try {
            Connection cn = null;
            Class.forName("com.mysql.jdbc.Driver");
            cn = DriverManager.getConnection("jdbc:mysql://localhost/car_inventory_system", "root", "");
            pst = cn.prepareStatement("SELECT * FROM employee_registration_master WHERE f_name = ? OR l_name = ?");
            pst.setString(1, txtSearch.getText());
            pst.setString(2, txtSearch.getText());
            r = pst.executeQuery();
            employee e;
            int i = 0;
            JLabel imageLabel = new JLabel();
            while (r.next()) {
                jTable1.setValueAt(r.getInt("emp_code"), i, 0);
                jTable1.setValueAt(r.getString("f_name"), i, 1);
                jTable1.setValueAt(r.getString("l_name"), i, 2);
                jTable1.setValueAt(r.getInt("age"), i, 3);
                jTable1.setValueAt(r.getString("birth"), i, 4);
                jTable1.setValueAt(r.getString("nationality"), i, 5);
                jTable1.setValueAt(r.getString("gender"), i, 6);
                jTable1.setValueAt(r.getString("contact"), i, 7);
                jTable1.setValueAt(r.getString("contact2"), i, 8);
                jTable1.setValueAt(r.getString("address"), i, 9);
                jTable1.setValueAt(r.getInt("gov_id"), i, 10);
                jTable1.setValueAt(r.getString("passport_no"), i, 11);
                if (r.getString("profile") != null) {
                    ImageIcon MyImage = new ImageIcon(r.getString("profile"));
                    Image img = MyImage.getImage();
                    Image newImg = img.getScaledInstance(70, 5, Image.SCALE_SMOOTH);
                    ImageIcon image = new ImageIcon(newImg);
                    jTable1.setValueAt(imageLabel.setIcon(image), i, 12); // Error: 'void' type not allowed here
                }
                i++;
            }
            pst.close();
            cn.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    } 

共有1个答案

温源
2023-03-14

简单地说,您需要重写tablemodelsetvalueat。当单元格“停止”编辑时,它会通知JTableJTable获取单元格值并调用TableModelsetValueat方法。然后,您需要根据模型的需求更新模型,并生成一个合适的修改事件。

例如...

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();

                List<Employee> employees = new ArrayList<>(25);
                employees.add(new Employee(1, "Jack", "Dourcy", 28, "03-11-2000", "American", "Male", "No of your business", "Stop spamming me", "Some place, some where", 45, "123456789", "Smiley"));

                JTable table = new JTable();
                TheModel model = new TheModel(employees);

                table.setModel(model);

                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Employee {

        private Integer emp_code;
        private String f_name;
        private String l_name;
        private Integer age;
        private String birth;
        private String nationality;
        private String gender;
        private String contact;
        private String contact2;
        private String address;
        private Integer gov_id;
        private String passport_no;
        private String profile;

        public Employee(Integer emp_code, String f_name, String l_name, Integer age, String birth, String nationality, String gender, String contact, String contact2, String address, Integer gov_id, String passport_no, String profile) {
            this.emp_code = emp_code;
            this.f_name = f_name;
            this.l_name = l_name;
            this.age = age;
            this.birth = birth;
            this.nationality = nationality;
            this.gender = gender;
            this.contact = contact;
            this.contact2 = contact2;
            this.address = address;
            this.gov_id = gov_id;
            this.passport_no = passport_no;
            this.profile = profile;
        }

        public Integer getEmp_code() {
            return emp_code;
        }

        public void setEmp_code(Integer emp_code) {
            this.emp_code = emp_code;
        }

        public String getF_name() {
            return f_name;
        }

        public void setF_name(String f_name) {
            this.f_name = f_name;
        }

        public String getL_name() {
            return l_name;
        }

        public void setL_name(String l_name) {
            this.l_name = l_name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getBirth() {
            return birth;
        }

        public void setBirth(String birth) {
            this.birth = birth;
        }

        public String getNationality() {
            return nationality;
        }

        public void setNationality(String nationality) {
            this.nationality = nationality;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getContact() {
            return contact;
        }

        public void setContact(String contact) {
            this.contact = contact;
        }

        public String getContact2() {
            return contact2;
        }

        public void setContact2(String contact2) {
            this.contact2 = contact2;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public Integer getGov_id() {
            return gov_id;
        }

        public void setGov_id(Integer gov_id) {
            this.gov_id = gov_id;
        }

        public String getPassport_no() {
            return passport_no;
        }

        public void setPassport_no(String passport_no) {
            this.passport_no = passport_no;
        }

        public String getProfile() {
            return profile;
        }

        public void setProfile(String profile) {
            this.profile = profile;
        }

    }

    public class TheModel extends AbstractTableModel {

        private List<Employee> employees;

        private String[] columns = new String[] {
            "Code", "First name", "Last name", "Age", "Birth date", "Nationality",
            "Gender", "Contact", "Contact", "Address", "Gov. Id", "Pass", "Profile"
        };

        public TheModel(List<Employee> employees) {
            this.employees = employees;
        }

        public Class getColumnClass(int column) {
            switch (column) {
                case 0:
                case 3:
                case 10: return Integer.class;
                default: return String.class;
            }
        }

        public int getRowCount() {
            return employees.size();
        }

        public int getColumnCount() {
            return columns.length;

        }

        public String getColumnName(int col) {
            return this.columns[col];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            Employee employee = employees.get(rowIndex);
            switch (columnIndex) {
                case 0: return employee.getEmp_code();
                case 1: return employee.getF_name();
                case 2: return employee.getL_name();
                case 3: return employee.getAge();
                case 4: return employee.getBirth();
                case 5: return employee.getNationality();
                case 6: return employee.getGender();
                case 7: return employee.getContact();
                case 8: return employee.getContact2();
                case 9: return employee.getAddress();
                case 10: return employee.getGov_id();
                case 11: return employee.getPassport_no();
                case 12: return employee.getProfile();
            }
            return null;
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 1:
                case 2: return true;
                default: return false;
            }
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            Employee employee = employees.get(rowIndex);
            switch (columnIndex) {
                case 1:
                    if (aValue instanceof String) {
                        String newValue = (String)aValue;
                        employee.setF_name(newValue);
                    }
                case 2:
                    if (aValue instanceof String) {
                        String newValue = (String)aValue;
                        employee.setL_name(newValue);
                    }
            }

            fireTableCellUpdated(rowIndex, columnIndex);
        }

    }
}

请注意,我已经更新了模型,以便直接利用员工POJO,而不是利用数组和其他东西。

 类似资料:
  • 我在Java的JTable中使用changeSelection(int row,int column,boolean toggle,boolean extended)。我这样做了,当表中有一个复选框列并且该列被单击时,就会发送一个事件来显示现在该行已被选中/取消选中--当用户执行该操作时,这一切都很好。但当它以编程方式完成时,事件被激发,但JTable没有刷新呈现器,难道我应该添加其他东西。它应该

  • 问题内容: 我试图以编程方式开始在按键上编辑当前行的第三列。 我实现了一个KeyListener,其中包含以下代码 当我释放Enter时,单元格确实是可编辑的(我可以在末尾键入),但是没有插入符号。 当我用鼠标单击时,行为是预期的(我可以进行编辑,并且存在carret)。 另外,我注意到在释放键时,我的celleditor为null,而在mouseclick上,它也不为null。 我究竟做错了什么

  • 我在stackoverflow上看到过类似的问题,但无论如何,我无法用这些答案解决我的问题。 我想做的是: 单击JTable中的double on单元格(由于IsCelledTable方法,该单元格可以编辑) 在自定义表中保存单元格的新值以打印此新值 更新我的数据库(SQlite)中的数据 这是我的自定义表模型 . 这是我打印JTable的JPanel:

  • 我现在可以更改为Visual Studio代码编辑器吗?在使用Git bash的同时,会不会在以后的作品中造成什么问题呢?我仍然没有找到这个问题的答案。但我想,我现在会得到我的答案。提前谢谢你。