JTable 单元格更改上的 JAVA 更新数据库

标签 java mysql swing jtable updates

我对 Java 很菜鸟(这不是什么新鲜事),而且我找不到一个好的教程。我使用 jTable 来显示一个表,其中填充了 MySQL 数据库中的数据。

到目前为止一切顺利,我得到了 table :

table preview

标准,您可以单击表格单元格,它会更改为可以填充新内容的文本字段。你们都知道这一点,但我如何使用它来更新数据库中的值?

我的代码:

import [...];
public class table extends JPanel {
    public String table;
    private Database db;

    public table(String tablename, Database db){

        try {
            table = tablename;
            this.db = db;

            //Get table with and height
            ResultSet res = db.query("SELECT COUNT( * ) FROM `"+table+"`");
            ResultSet res2 = db.query("SELECT COUNT( * ) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"+table+"'");

            int rows = 0;
            int collums = 0;

            res.next();
            res2.next();

            rows = res.getInt(1);
            collums = res2.getInt(1);

            //Get table column names and set then in array
            ResultSet clom = db.query("DESCRIBE  `"+table+"`");

            String[] columnNames = new String[collums];

            int s = 0;

            while(clom.next()){
                columnNames[s] = clom.getString(1);
                s++;
            }

            //get table data and put in array
            Object[][] data = new Object[rows][collums];

            ResultSet result = db.query("SELECT * FROM `"+table+"`");

            int q = 0;

            while(result.next()){
                for(int a=0; a<= (collums - 1); a++){
                    data[q][a] = result.getString(a + 1);
                    //System.out.println(q + " - " + a);
                }
                q++;
            }

            //Make Jtable of the db result form the two array's
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);

            // do some event listening for cell change

            JScrollPane scrollPane = new JScrollPane(table);
            JFrame frame = new JFrame("table editor");
            scrollPane.setOpaque(true);
            frame.setContentPane(scrollPane);
            frame.pack();
            frame.setSize(600, 800);
            frame.setVisible(true);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
}

我想我需要绑定(bind)某种表监听器,当某些内容发生变化时,我会获取表中的所有值并使用查询更新它们。

我该怎么做?

这是我的伪代码:

table.bindCellEventListner(callback(t){
     Array row = t.getAllValuesAsArrayOfRow();

     String data = "";

     int f = 0
     while(row.next()){
         data .= "`"+clom[f]+"` = '"+row[f]+"',"
         f++;
     }
     data.delLastChar();
     db.query("UPDATE `"+table+"` SET "+data+" WHERE `id` ="+row[0]+";");

});

最佳答案

删除的答案抄袭了 Rachel Swailes 14 年前的答案,发现 here 。为了完整起见,并且因为答案正确且有用,我在此处引用了相关文字:

Step 1: It's going to be way easier for the whole thing if you make your table extend a TableModel from now (if you haven't already). So if you need help with that just ask.

Step 2: In the table model you need to enable the cells to be editable. In the TableModel class that you make, you need to add these methods

public boolean isCellEditable(int row, int col) { 
  return true; 
}

public void setValueAt(Object value, int row, int col) {
  rowData[row][col] = value;
  fireTableCellUpdated(row, col);
}

Step 3: You will see in the second method that we fire a method called fireTableCellUpdated. So here we can catch what the use it changing. You need to add a TableModelListener to your table to catch this.

mytable.getModel().addTableModelListener(yourClass);

And in the class that you decide will implement the TableModelListener you need this

public void tableChanged(TableModelEvent e) {
  int row = e.getFirstRow();
  int column = e.getColumn();
  TableModel model = (TableModel)e.getSource();
  Object data = model.getValueAt(row, column);
  ...
}

now you have the data in the cell and the place in the grid where the

cell is so you can use the data as you want

关于JTable 单元格更改上的 JAVA 更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232118/

相关文章:

java - 出于 glasspane 的目的,为什么 Swing 中的输入元素似乎不被视为 JPanel 的一部分?

java - 类转换异常 - tabbedpane.getComponentAt(index)

java - 框架中有多个 JPanel/具有背景图像和顶部有组件的另一层

java - 手动分配 ID 时,Spring Data MongoDB 注释 @CreatedDate 不起作用

java - 如何解决 java.util.zip.ZipException 重复条目 : com/google/gson/annotations/Expose. 类?

MySQL 使用 UUID_SHORT() 函数

mysql - 从每小时获取三个随机日期

mysql - 统计MySQL当月数据

java - 如何在具有另一个组件的拆分 Pane 上添加按钮

java - Kafka 连接 API 客户端