1

如果它们有值,我正在尝试更改 JTable 第三行的单元格的颜色。我读到这样做的一个好方法是使用表格单元格渲染器。但是,它似乎什么也没做!这是我的渲染代码:

public class RenderTablaPrestamos extends DefaultTableCellRenderer{

   @Override
   public Component getTableCellRendererComponent (JTable tabla, Object valor,
                                                boolean isSelected, boolean hasFocus,
                                                int row, int col){
    JLabel celda = (JLabel) super.getTableCellRendererComponent(tabla, valor, isSelected, hasFocus, row, col);

        if(valor instanceof Integer){
            Integer v=(Integer)valor;
            if(col==3){
                if(valor!=null){
                     celda.setBackground(Color.red);
                }
                else{
                    celda.setBackground(Color.WHITE);
                }
            }
            else{
                celda.setBackground(Color.WHITE);
            }
        }
    return celda;
    }
}

这里是我如何使用我的渲染器:

tablaUsuariosPrestamos.setDefaultRenderer(Object.class,new RenderTablaPrestamos());

这是我的 JTable 的图片(我认为模型代码没有什么用,因为它有点长):

在此处输入图像描述

我不认为它与if clausules有任何关系,因为我评论过它们并且它也不起作用。

我哪里错了?

4

2 回答 2

2

采用

for (int i = 0; i < tabla.getColumnCount(); i++) {
    tabla.getColumnModel().getColumn(i).setCellRenderer(new RenderTablaPrestamos());
}

代替

tablaUsuariosPrestamos.setDefaultRenderer(Object.class,new RenderTablaPrestamos());
于 2017-02-26T16:55:22.823 回答
1

函数中的代码setDefaultRenderer按预期:

final YourCellRenderer cellRenderer = new YourCellRenderer();
YourTableModel stModel = new YourTableModel();
table = new JTable(stModel);

table.setDefaultRenderer(YourComponent.class, cellRenderer);

它似乎没有渲染的原因是,当您将 映射YourComponent.class到渲染器时,它没有触发,因为YourTableModel认为该类是Object.

要更正此问题,您需要覆盖类中的getColumnClass方法YourTableModel

public class YourTableModel extends AbstractTableModel {

    ...

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return YourComponent.class;
    }
    ...
}
于 2021-07-01T14:53:05.887 回答