我正在 Eclipse 下使用 Java 和 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 包含具有重写方法的类 vector 。
如果我在 vector 中添加一个像这样的元素 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”相比,您犯了同样的错误。
第二个错误是您使用 View 索引在模型中建立索引。 JTable.prepareRenderer
方法中传递的 row
和 column
参数是 View 索引。您不能像在 getModel().getValueAt(row, column)
中那样使用它们来索引模型。您需要使用 JTable.convertRowIndexToModel
转换这些索引和 JTable.convertColumnIndexToModel
在调用 getModel().getValueAt() 之前。您可以在 JTable documentation 的介绍性描述中阅读更多相关信息。 .
或者,使用 JTable.getValueAt()
反而。在这里您可以使用传递给 JTable.prepareRenderer
的 View 索引。
关于java - 当我将 xml 中的数据放入我的 customJTable 时,"prepareRenderer"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44070892/