自定义jtable单元格显示方式

自定义jtable显示方式,需要继承DefaultTableCellRenderer
然后重写
public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column)

{
//指定用什么控件显示和显示什么值,value是table对应的model的row行column的值,如果不想显示这个值,可以在这修改,如combox就有key和text的区别,显示给用户text,但是保存到model是key,这时就可以在则根据value获取对应的text,然后显示出来
}



最后
table.setDefaultRenderer(Object.class, new MyCellRender());


例子:
public class PosParamCellRender extends DefaultTableCellRenderer 
{
	protected PosParam posParam;
	
	public PosParamCellRender()
	{
		super();
		posParam = null;
	}
	

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column)
	{
		
		if(column == 1)
		{
			PosParamModel model = (PosParamModel)table.getModel();
			posParam = model.getPosParam(row);
			posParam.setValue(value);
		//	posParam.getComponent().setOpaque(true);  
		//	posParam.getComponent().
			//posParam.getComponent().setBackground(isSelected ? table.getSelectionBackground() : new Color(255,255,200));   
			//posParam.getComponent().setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); 
			//return posParam.getComponent();
			if(posParam.getParaBean().getValueType().equals(ParamType.COMBOX))
			{
				OptionComboBox cbx = (OptionComboBox)posParam.getComponent();
				value = (String)cbx.getSelectedItem();
			}
		}
		else
		{
			posParam = null;
		}
		return super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
				row, column);
	}



	@Override
	protected void setValue(Object value)
	{
		if(posParam != null)
		{
	//		posParam.setValue(value);
		}
		super.setValue(value);
	}


	
}



你可能感兴趣的:(jtable)