JTable实现C列放入复选框

1,MyTableModel 继承 DefaultTableModel类,主要增加:

成员变量
Class[] typeArray = {Object.class,Object.class,Object.class,Object.class, Object.class, Boolean.class};
方法
public void selectAllOrNull(boolean value){
      // Select All. The last column
 	for(int index = 0; index < getRowCount(); index ++){
        this.setValueAt(value, index, 5);
    }
}
	
public Class getColumnClass(int columnIndex) {  
       return typeArray[columnIndex];// 返回每一列的数据类型   
}

2、设置C列数据为Boolean类型,如

new Object[][] {
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)},
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)},
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)},
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)},
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)},
				{ 1+"",2+"",3+"",4+"",5+"",new Boolean(false)}};

3、若不需要表头也为复选框,可不设置TableHeader

	TableColumn column = table.getColumnModel().getColumn(5);
	column.setCellEditor(new DefaultCellEditor(new JCheckBox()));
	table.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(table));

4、书写主要渲染类

class CheckHeaderCellRenderer implements TableCellRenderer {
	MyTableModel tableModel;
	JTableHeader tableHeader;
	final JCheckBox selectBox;

	public CheckHeaderCellRenderer(final JTable table) {
		this.tableModel = (MyTableModel) table.getModel();
		this.tableHeader = table.getTableHeader();
		selectBox = new JCheckBox(tableModel.getColumnName(5));
		selectBox.setSelected(false);
		tableHeader.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() > 0) {
					// 获得选中列
					int selectColumn = tableHeader.columnAtPoint(e.getPoint());
					if (selectColumn == 5) {
						boolean value = !selectBox.isSelected();
						selectBox.setSelected(value);
						tableModel.selectAllOrNull(value);
						tableHeader.repaint();
					}
				}
			}
		});
	}

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		// TODO Auto-generated method stub
		String valueStr = (String) value;
		JLabel label = new JLabel(valueStr);
		label.setHorizontalAlignment(SwingConstants.CENTER); // 表头标签剧中
		selectBox.setHorizontalAlignment(SwingConstants.CENTER);// 表头标签剧中
		selectBox.setBorderPainted(true);
		JComponent component = (column == 5) ? selectBox : label;

		component.setForeground(tableHeader.getForeground());
		component.setBackground(tableHeader.getBackground());
		component.setFont(tableHeader.getFont());
		component.setBorder(UIManager.getBorder("TableHeader.cellBorder"));

		return component;
	}
}

你可能感兴趣的:(java,SE)