jtable每行每列的单元格的编辑器都可以自定义,
方法如下:
继承 DefaultCellEditor
然后重新
和
最后
table.setDefaultEditor(Object.class, new MyCellEditor());
例子
方法如下:
继承 DefaultCellEditor
然后重新
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column)
{
指定用什么控件作为编辑器,并且在这初始化控件的值,可以根据row和column指定每个单元格的编辑器,row和column都是该单元格在jtable对应的model的行列
value是单元格对应的数据model的值,
这里要把使用的控件保持成全局变量,以便在getCellEditorValue获取值。
}
和
public Object getCellEditorValue()
{
编辑结束后调用这个方法,返回结果,一般是直接返回控件的值
}
最后
table.setDefaultEditor(Object.class, new MyCellEditor());
例子
public class PosParamCellEditor extends DefaultCellEditor
{
protected PosParam posParam;
public PosParamCellEditor()
{
super(new JTextField());
posParam = null;
}
public PosParamCellEditor(JComboBox box)
{
super(box);
posParam = null;
}
public PosParamCellEditor(JCheckBox chb)
{
super(chb);
posParam = null;
}
public PosParamCellEditor(JTextField txt)
{
super(txt);
posParam = null;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column)
{
// TODO 当单元格处于编辑状态时
if(column == 1)
{
PosParamModel model = (PosParamModel)table.getModel();
posParam = model.getPosParam(row);
posParam.setValue(value);
posParam.getComponent().setOpaque(true);
// posParam.getComponent().setBackground(isSelected ? table.getSelectionBackground() : new Color(255,255,200));
// posParam.getComponent().setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
return posParam.getComponent();
}
posParam = null;
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
@Override
public Object getCellEditorValue()
{
if(this.posParam == null) return super.getCellEditorValue();
return posParam.getValue();
}
}