0

I have JTable with name 'tableEarnings' it consist of 3 columns:

  • check
  • Earnings
  • Description and a
  • jButton

Every cell in 'check' column have a checkbox. I need to fetch checked values of 'Earnings' and 'Description' cell from JTable and store it to a database when I click jButton please help me

This my code for button listener:

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
    //System.out.println("table"+tableEarnings.getModel().getRowCount());
    for (int i = 0; i < tableEarnings.getModel().getRowCount()+1; i++) {    
        if ((Boolean) tableEarnings.getModel().getValueAt(i, 0)) {
           System.out.println("Value" + tableEarnings.getValueAt(i, 1));
           break;
        }
    }
}
dic19
  • 17,821
  • 6
  • 40
  • 69
Jipin Gopi
  • 25
  • 2
  • 7

1 Answers1

3

There are three simple mistakes in your loop iterating over the table model:

  1. Top bound for i variable should be row count - 1. Otherwise you will probably get an exception (i.e.: ArrayIndexOutOfBoundsException if your table model is DefaultTableModel)

  2. If you find a true boolean value then don't break the loop. By doing this you lose all rows further than i index.

  3. You are printing the value calling getValueAt() directly on the table (view) not the model. This might not retrieve the correct value if your table is sorted or columns were reordered. Always keep consistency. In this case you should work with the model.

For example:

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
    TableModel model = tableEarnings.getModel();
    for (int i = 0; i < model.getRowCount() - 1; i++) {    
        if ((Boolean) model.getValueAt(i, 0)) {
           System.out.println("Value" + model.getValueAt(i, 1));
        }
    }
}

Now you will be able to print the values.

If everything goes well you have the basis now to insert the rows in your database. But be aware that database calls are time consuming tasks and may block the Event Dispatch Thread (EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing lesson.

dic19
  • 17,821
  • 6
  • 40
  • 69