当我将 xml 中的数据放入我的 customJTable 时,"prepareRenderer" 不起作用

"prepareRenderer" doesn't work when I put data from xml into my customJTable

我正在使用 Java 和 Eclipse 下的 Swing 进行个人项目。

我有一个自定义 JTable 来呈现单元格。

public class CustomJTable extends JTable{

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
    Component c = super.prepareRenderer(renderer, row, column);

    // change background of rows if [row,13] is even
    c.setBackground(getBackground());
    if( (int)getModel().getValueAt(row, 13) %2 == 0)
        c.setBackground(Color.YELLOW);

    // change font, border e background of cells if a string field is equal to some predeterminated value
    Font myFont = new Font(TOOL_TIP_TEXT_KEY, Font.ITALIC | Font.BOLD, 12);
    c.setForeground(getForeground());

    if (getModel().getValueAt(row, column)=="VALUE"){
        ((JComponent) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); //needs cast for using setBorder
        c.setFont(myFont);
        c.setForeground(Color.RED);
        c.setBackground(new Color(255, 230, 230));
    }

    //set disabled cells appearance
    if (getModel().getValueAt(row, column)=="DISABLED"){
        ((JComponent) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.GRAY));
        c.setForeground(Color.LIGHT_GRAY);
        c.setBackground(Color.LIGHT_GRAY);
    }

    return c;
}

我的 CustomJTable 从自定义 TableModel(扩展 AbstractTableModel)中获取值,该自定义 TableModel 包含一个 class 的向量,具有覆盖的方法。

如果我用这样的东西在向量中添加一个元素 myModel.getVector().add(element) 我没问题。 在我输入 myTable.updateUI() 之后,Row 会自动添加到 CustomJtable 中,并且正确并呈现。一切都很完美!!!

当我尝试从我之前保存的外部 .XML 添加行时出现问题。 我添加到我的 JTable 的数据是正确的,黄色行背景也发生了变化,但单元格没有呈现(不是单元格边框,不是字体变化,不是红色单元格背景)。

我什么都试过了。 validate()repaint()fireTableCellChanged()... 我找不到错误。谁能帮帮我?

getModel().getValueAt(row, column)=="VALUE" >> 这很可能已经是一个错误。如果你想比较字符串,你需要使用 Object.equals 来比较它们。像这样:"VALUE".equals(getModel().getValueAt(row, column).toString())。与字符串 "DISABLED".

相比,你犯了同样的错误。

第二个错误是您使用视图索引在模型中建立索引。 JTable.prepareRenderer方法中传入的rowcolumn参数是视图索引。您不能像在 getModel().getValueAt(row, column) 中那样使用它们来索引模型。您需要使用 JTable.convertRowIndexToModel and JTable.convertColumnIndexToModel before calling getModel().getValueAt(). You can read more about this in the introductory description in the JTable documentation.

翻译这些索引

或者,使用 JTable.getValueAt()。在这里您可以使用传递给 JTable.prepareRenderer.

的视图索引