0

I have a JTable with data from a database. 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. I've tried running an update SQL command to push the new data but it does not update. 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. 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.

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(){

    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():

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);

    }


}
3
  • Ok I got the Update working one time. Now while testing I am getting duplicate println(s) each time I edit an entry in the table the println exponentially grows by two. Nov 19, 2015 at 22:28
  • Add the ListSelectionListener to the ListSelectionModel when the table is created, NOT every time you click on the button.
    – camickr
    Nov 20, 2015 at 0:40
  • @camickr thanks again this helped me narrow it down some more.. But it appears that no matter where I put it the number of outputs increases each time I the ListSelectionListener is started. I have researched and found that I can use !e.getValueIsAdjusting but did not resolve the issue. I appreciate your time you are giving to help with this issue. Nov 20, 2015 at 15:12

3 Answers 3

3

you can try adding TableModelListener this way which executes once the table has changed. 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          
    }
});
2

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:

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:

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();
1
  • Thanks! This did work. I have a few more bugs to work through I updated what is happening now. I know that your code worked I was able to save one entry without error. But a new issue has come up Nov 19, 2015 at 22:42
0

I finally figured out why it was duplicating thanks to @camickr for pointing out that it was creating multiple Listeners. 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();
                    }
                });
            }
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.