比如下面这个tabel(第一列是boolean,tabel会自动将绘制器和编辑器设置为checkbox)
我想让第一列实现动态的灰化,也就是让里面的checkbox.setEnable(false);
比如用两个按钮来控制,一个灰化按钮,一个亮化按钮
点击灰化按钮,第一列就不可编辑,点击亮化按钮,第一列变为可编辑
jTable1 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"选择", "用户名", "密码"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
------解决方案--------------------
全部代码,包括测试类代码如下:
package mine.test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
public class TestMain {
public static void main(String[] args){
JFrame frame=new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyModel model=new MyModel(5,6);
final JTable table=new JTable(model);
table.setDefaultRenderer(Boolean.class, new MyRenderer());
frame.getContentPane().add(table,BorderLayout.CENTER);
JButton buttong=new JButton("disable");
buttong.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
MyModel mode=(MyModel) table.getModel();
mode.setCheckEnable(false);
mode.fireTableDataChanged();
}
});
frame.getContentPane().add(buttong,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
}
package mine.test;
import javax.swing.table.DefaultTableModel;
public class MyModel extends DefaultTableModel{
private boolean editable=true;
public MyModel(int c ,int r){
super(c,r);
}
@Override
public boolean isCellEditable(int row, int column) {
// TODO Auto-generated method stub
//假设checkbox在第一列
return column==0 ? editable : super.isCellEditable(row, column);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
// TODO Auto-generated method stub
return columnIndex==0? Boolean.class: super.getColumnClass(columnIndex);
}
public void setCheckEnable(boolean b){
this.editable=b;
}
}
package mine.test;
import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
public class MyRenderer extends JCheckBox implements TableCellRenderer{
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public MyRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
setBorderPainted(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {