JTable行背景颜色不会更改为Double或Integer

时间:2014-11-17 09:21:55

标签: java string swing jtable tablecellrenderer

我正在使用以下代码更改JTable中行的背景颜色。 对于具有String值的所有单元格,行的颜色会更改,但对于具有Integer或Double值的单元格,它不会更改。

  private JTable getNewRenderedTable(final JTable table) {
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                String status = (String)table.getModel().getValueAt(row, index);
                if (Constants.seller.equals(status)) {
                    c.setBackground(Color.GRAY);
                    //setForeground(Color.WHITE);
                } else {
                    c.setBackground(table.getBackground());
                    c.setForeground(table.getForeground());
                }       
                return c;
            }   
        });
        return table;
    }

1 个答案:

答案 0 :(得分:1)

尝试为Integer和Double注册相同的渲染器。默认情况下,这些类具有单独的默认渲染器。这样的事情。

private JTable getNewRenderedTable(final JTable table) {
    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            String status = (String)table.getModel().getValueAt(row, index);
            if (Constants.seller.equals(status)) {
                c.setBackground(Color.GRAY);
                //setForeground(Color.WHITE);
            } else {
                c.setBackground(table.getBackground());
                c.setForeground(table.getForeground());
            }       
            return c;
        }   
    });
    table.setDefaultRenderer(Number.class, table.getDefaultRenderer(Object.class));
    table.setDefaultRenderer(Double.class, table.getDefaultRenderer(Object.class));
    return table;
}