简体   繁体   中英

How to get content of JTable if cell contains checkbox

I have created a JTable in Netbeans of which the first column consists of checkboxes.

These checkboxes were made by adding

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

and

jTable1.getColumn("ColumnName").setCellEditor(new DefaultCellEditor(checkBox)); 

under customize code when right-clicking the JTable. And in the Table Contents I specified the datatype to Boolean (I basically followed along the instructions on this website since I had never worked with JTables before: http://forums.netbeans.org/topic9007.html )

My question now: how do I get the actual checkbox in row=1 & coloumn=1, for example? These attempts aren't working:

JCheckBox j = (JCheckBox) jTable1.getComponent(1);

JCheckBox j = (JCheckBox) jTable1.getModel().getValueAt(1, 1);

I get the error message "java.lang.String cannot be cast to javax.swing.JCheckBox" .

For what I'm trying to do, I need to get back the object/component of type "checkbox" and NOT just find out if it is selected or not. Is that possible to do? I'm not super advanced in programming, so that's why I'm having trouble.

EDIT : old answer below, was reminded that going through the TableModel to get the boolean value directly is a safer bet than messing about with JTable UI :)

Don't try to cast anything to JCheckBox , instead iterate through the Model to get to the values you want.


The Component list includes everything defined within the Object , so you might not always get the specific element you want.

I recommend looping through the Components and using instanceof to check if it matches JCheckBox .

for(Component c : jTable1.getComponents[]) {
    if(c instanceof javax.swing.JCheckBox) {
        // do the stuff
    } else {
        // don't do the stuff
    }
}

Or even iterate through the Components in the first column, might make things easier.

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