saba
saba

Reputation: 11

checkbox on jtable and getting values of corresponding rows in java swing

I add checkbox in JTable.I want to get values of particular cells of the selected JCheckBox rows.adding checkbox code is like

JCheckBox checkBox = new javax.swing.JCheckBox();
jTable1 = new javax.swing.JTable();

jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {    },
new String [] {
    "Station", "OperationName", "TliScantime", "StartTime", "Completedtime", "TliScanTime-StartTime", "StartTime-CompletedTime", "Select"
}
) {
Class[] types = new Class [] {
    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
};

public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
}
});
jTable1.getColumn("Select").setCellEditor(new DefaultCellEditor(checkBox));

in netbeans.

I use addListSelectionListener for clicking on cells of JCheckBox of JTable.

 jTable1.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent event ) {
                   // if(jTable1.getValueAt(0,7).equals(true)){
                       Object b=jTable1.getValueAt(0,7);

                       System.out.println(b); 
                   //}    

                }
            }); 

I donot understand why it is print null at first time and after that it will print value 2 times.

Upvotes: 1

Views: 7959

Answers (2)

camickr
camickr

Reputation: 324197

There is no need to create and assign a custom editor. JTable will return the appropriate renderer and editor based on the class returned from the getColumnClass(,..) method. A checkbox is automatically used for Boolean data.

A ListSelectionListener fires two events, one for the deselection of the previously selected row and one for selecting the current row.

Upvotes: 2

John Gardner
John Gardner

Reputation: 25146

before clicking any cells, the value in that field is null (i don't see you setting any content to your table in the example code)

after checking a checkbox in cell, it will now have an explicit true value as set by the checkbox.

after clicking it again, it will have an explicitly set null value, set by the checkbox.

Upvotes: 1

Related Questions