我有一个jTable
两列。第一列设置为布尔值(用于复选框),第二列具有字符串值。当我使用时Netbeans
,复选框被添加到第一列的所有行中。我试图只为那些在第二列中具有值的行添加它。我用代码来尝试,
private class CustomCellRenderer extends DefaultTableCellRenderer {
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
@Override
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
Component rendererComp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,row, column);
for(int i=row;i<jTable1.getRowCount();i++){
if(jTable1.getValueAt(i, 1)==null){
jTable1.setValueAt(true, i, 0);
//checkbox.setOpaque(false);
}
}
return this ;
}
}
如果我尝试为上述 for 循环中的所有其他复选框设置值“true”,它运行良好。如何将其设置为对其余行不可见。
编辑:
我在这个添加我的代码
package e2;
import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class JTable_CheckBox extends javax.swing.JFrame {
/** Creates new form JTable_CheckBox */
JCheckBox checkbox=new JCheckBox();
public JTable_CheckBox() {
initComponents();
jTable1.setValueAt("John",0,1);
jTable1.setValueAt("James",1,1);
jTable1.setValueAt("Janet",2,1);
jTable1.setValueAt("Tom",3,1);
jTable1.getColumnModel().getColumn(0).setCellRenderer(new CheckboxCellRenderer());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTable_CheckBox().setVisible(true);
}
});
}
public class CheckboxCellRenderer extends JCheckBox implements TableCellRenderer {
public CheckboxCellRenderer() {
setOpaque(false);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
//here i am trying to set check box invisible,but here i am setting as selected
for(int i=row;i<table.getRowCount();i++){
if(table.getValueAt(i, 1)==null){
table.setValueAt(true, i, 0);
//checkbox.setOpaque(false);
}
}
return this;
}
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}