简体   繁体   中英

How to change background and format of a cell in a JTable

in my custom JTable I have multiple columns. One column is of type java.sql.Timestamp. I want to change the backgroundcolor of all cells and I want to change the format of only the Timestamp cells. I made the following customcellrenderer which I call by:

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());
            }
        }
    }
}

The setValue only works if getTableCellRendererComponent is commented out.

How can I get both to work?

The setValue() should call delegate.setText() because the delegate's component is actually used. Also I don't even see where the setValue() is called in the renderer.

Call it in your renderer passing the Object value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM