日期:2014-05-20 浏览次数:20742 次
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) {