简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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