如何更改JTable中单元格的背景和格式

时间:2015-08-11 10:49:43

标签: java swing jtable timestamp tablecellrenderer

在我的自定义JTable中我有多列。一列的类型为java.sql.Timestamp。我想更改所有单元格的背景颜色,我想更改时间戳单元格的格式。我做了下面的customcellrenderer,我打电话给:

for(int i = 0; i < tableTask.getColumnCount(); i++)
{
    Class columnClass = myTaskTM.getColumnClass(i);
    TableCellRenderer defaultRenderer = tableTask.getDefaultRenderer(columnClass);
    tableTask.getColumnModel().getColumn(i).setCellRenderer(new CustomRenderer(defaultRenderer));
}

customrenderer:

public class CustomRenderer extends DefaultTableCellRenderer
{
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    TableCellRenderer delegate;

    public CustomRenderer(TableCellRenderer defaultRenderer)
    {
        super();
        delegate = defaultRenderer;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component c = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        Color foreground, background;

        if(!isSelected)
        {
            ...
        }
        else
        {
            background = javax.swing.UIManager.getDefaults().getColor("Table.selectionBackground");
            //foreground = javax.swing.UIManager.getDefaults().getColor("Table.selectionForeground");
            foreground = Color.BLACK;
        }

        c.setForeground(foreground);
        c.setBackground(background);

        setValue(value);

        return c;
    }

    @Override
    public void setValue(Object value) {
        if (formatter == null) {
            formatter = DateFormat.getDateInstance();
        }
        if(value != null)
        {
            if(value.getClass().toString().equals("class java.sql.Timestamp"))
            {
                ((JLabel)delegate).setText((value == null) ? "" : formatter.format(value));
            }
            else
            {
                ((JLabel)delegate).setText(value.toString());
            }
        }
    }
}

只有在getTableCellRendererComponent被注释掉时,setValue才有效。

我怎样才能让两者兼顾?

1 个答案:

答案 0 :(得分:1)

setValue()应调用delegate.setText(),因为实际使用了代理的组件。此外,我甚至不知道在渲染器中调用setValue()的位置。

在您的渲染器中调用它,传递Object value