自定义jtable单元格编辑器

jtable每行每列的单元格的编辑器都可以自定义,
方法如下:
继承 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();
}





}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值