简体   繁体   English

Jtable-编辑后获取表单元格数据

[英]Jtable - Get table cell data after edit

I have a JTable with data from a database. 我有一个JTable,其中包含来自数据库的数据。 I can pull the data that is currently in the table using 我可以使用以下方式提取表中当前的数据

table.getValueAt(table.getSelectedRow(),3)    

What I cannot figure out is how to get the same cell's new data after editing in running App. 我无法弄清楚的是,在运行App进行编辑后,如何获取同一单元格的新数据。 I've tried running an update SQL command to push the new data but it does not update. 我尝试运行更新SQL命令来推送新数据,但它不会更新。 I think I am missing a step. 我想我错过了一步。 I've also attempted TableModelListener but I have had very little luck getting it to work as I need it to. 我也尝试过TableModelListener,但运气不佳,无法按需使用。 This is what I have so far for assisting the retrieval and update of data: 到目前为止,这是我协助数据检索和更新的内容:

private void UpdateDbFromJTable(){
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        @Override
        public void valueChanged(ListSelectionEvent event) {
            if (table.getSelectedRow() > -1) {
                // print first column value from selected row
             String App = table.getValueAt(table.getSelectedRow(),0).toString();
             String Version = table.getValueAt(table.getSelectedRow(),1).toString();
             String Issue = table.getValueAt(table.getSelectedRow(),2).toString();
             String Resolved =table.getValueAt(table.getSelectedRow(),3).toString();


            try {
                String sql = "UPDATE Bugs SET Resolved =" + Resolved + "WHERE App = \" " + App + "' AND Version =\"" + Version + "\" AND Issue = \"" + Issue + "\"";
                conn = DriverManager.getConnection(DB_URL);
                stmt = conn.prepareStatement(sql);
                rs = stmt.executeUpdate();


            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);

            }
             }

        }

    });


}

The Update statement is incorrect at this point because it is just updating "Resolved" to what it was already set to in the DB. Update语句此时不正确,因为它只是将“ Resolved”更新为数据库中已设置的内容。

This is what is happening now that I have the update corrected. 现在,我已经更正了更新,这就是发生的情况。 I get duplicate 'println'(s) that grows every time I click save after making a change to a different table entry: private void UpdateDbFromJTable(){ 更改其他表条目后,每次单击“保存”,都会得到重复的“ println”,它们会增加:private void UpdateDbFromJTable(){

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        @Override
        public void valueChanged(ListSelectionEvent event) {
            String App = null;
            String Version = null;
            String Issue = null;
            String Resolved = null;
             if (! event.getValueIsAdjusting())
                {
            if (table.getSelectedRow() > -1) {
                // print first column value from selected row
                App = table.getValueAt(table.getSelectedRow(),0).toString();
                Version = table.getValueAt(table.getSelectedRow(),1).toString();
                Issue = table.getValueAt(table.getSelectedRow(),2).toString();
                Resolved =table.getValueAt(table.getSelectedRow(),3).toString();

                System.out.println(App + "  " + Version + "  " + Issue +  "  " + Resolved);
                }

                }
             if(table.isEditing()){
                    table.getCellEditor().stopCellEditing();

            try {


                conn = DriverManager.getConnection(DB_URL);
                String sql = "UPDATE Bugs SET Resolved = ? WHERE App = ? AND Version = ? AND Issue = ?";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, Resolved);
                stmt.setString(2, App);
                stmt.setString(3, Version);
                stmt.setString(4, Issue);
                stmt.executeUpdate();





            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);

            }
             }

        }

    });


}

My save Button: 我的保存按钮:

btnSave.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            UpdateDbFromJTable();
            JTable();

        }
    });

And My JTable(): 和我的JTable():

Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
private JTable table;
private void JTable() {
    String sql = "SELECT * FROM Bugs";
    try {
        conn = DriverManager.getConnection(DB_URL);
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();
        table.setModel(DbUtils.resultSetToTableModel(rs));



    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);

    }


}

I'm guessing your editor is still active so the data hasn't been saved to the model yet. 我猜您的编辑器仍然处于活动状态,因此数据尚未保存到模型中。

So you need to stop editing in your ActionListener: 因此,您需要在ActionListener中停止编辑:

if (table.isEditing())
     table.getCellEditor().stopCellEditing();

Check out Table Stop Editing for more information and another approach 查看表格停止编辑以获取更多信息和另一种方法

Also, use a PreparedStatment for your SQL it is easier to maintain and less error prone: 另外,对您的SQL使用PreparedStatment ,它更易于维护且不易出错:

String sql = "UPDATE Page SET Title = ? WHERE Name = ?";

PreparedStatement stmt = connection.prepareStatement(sql);

stmt.setString( 1, "update" );
stmt.setString( 2, "Name3" );
stmt.executeUpdate();
stmt.close();

you can try adding TableModelListener this way which executes once the table has changed. 您可以尝试以这种方式添加TableModelListener该方式将在表更改后执行。 Something like: 就像是:

tableModel.addTableModelListener(new TableModelListener(){
    @Override
    public void tableChanged(TableModelEvent tableModelEvent) {
        if(table.isEditing())
        String value = table.getValueAt(table.getSelectedRow(),3);    
        //do stuff  with value          
    }
});

I finally figured out why it was duplicating thanks to @camickr for pointing out that it was creating multiple Listeners. 我终于弄清楚了为什么要复制@camickr来指出它正在创建多个侦听器的原因。 I moved the listener around the button itself. 我在按钮本身周围移动了侦听器。

 table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent event) {

                if (!event.getValueIsAdjusting()) {
                    if (table.getSelectedRow() > -1) {
                        // print first column value from selected row
                        app = table.getValueAt(table.getSelectedRow(), 0).toString();
                        version = table.getValueAt(table.getSelectedRow(), 1).toString();
                        issue = table.getValueAt(table.getSelectedRow(), 2).toString();
                        resolved = table.getValueAt(table.getSelectedRow(), 3).toString();
                        System.out.println(app + "  " + version + "  " + issue + "  " + resolved);

                    }
                }
                btnSave.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {

                        updateDbFromJTable();
                        //jTable();
                    }
                });
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM