我的表模型中有这段代码:
public class DocumentProjectTableModel extends AbstractTableModel{
private List<MyDocument> myDocuments;
public String getValueAt(int row, int column) {
String toReturn = null;
MyDocument myDocument = myDocuments.get(row);
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
switch (column) {
case 0:
if(myDocument.getProject().getRegDate()!=null) toReturn = format.format(myDocument.getProject().getRegDate());
break;
case 1:
toReturn = myDocument.getProject().getRegNum();
break;
case 2:
toReturn = myDocument.getProject().getDescription();
break;
case 3:
toReturn = myDocument.getProject().getShortName();
break;
case 4:
toReturn = myDocument.getProject().getSecondName()+myDocument.getProject().getFirstName()+myDocument.getProject().getMiddleName();
break;
}
return toReturn;
}
// some other stuff is not shown
我想改变每一行的背景颜色,例如如果 myDocument.getIsRegistered() == true
,我希望这一行有黄色背景,如果 myDocument.getIsValid == false
行为蓝色等。
我找到了根据 JTable 中的值对行重新着色的示例。但是 getIsValid 和 getIsRegistered() 实际上并没有显示,它们只存在于模型中。任何建议或例子都会有帮助。提前致谢。
更新。我的 TableCellRenderer:
public class MyTableCellRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
String actualValue = (String) value;
// Set the colors as per the value in the cell...
if(actualValue.equals("lifesucks") ){
setBackground(Color.YELLOW);
}
return this;
}
}
使用渲染器:
int vColIndex = 0;
TableColumn col = resultTable.getColumnModel().getColumn(vColIndex);
col.setCellRenderer(new MyTableCellRenderer());
resultTable.setModel(new DocumentProjectTableModel(docs));
表格照常显示,没有黄色。为什么?
更新2。
resultTable=new JTable(new DocumentProjectTableModel(docs)){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on a cell value
if (!isRowSelected(row)) {
c.setBackground(getBackground());
int modelRow = convertRowIndexToModel(row);
String type = (String) getModel().getValueAt(modelRow, 0);
c.setBackground(Color.GREEN);
}
return c;
}
};
表是空的:(
最佳答案
因为你想为整行着色,所以它更容易使用 Table Row Rendering而不是创建多个自定义渲染器。
I've found examples that recolor rows depending on values in JTable. But getIsValid and getIsRegistered() aren't actually displayed, they exist only in model
您仍然可以从表中访问模型。你只需使用:
table.getModel().getValueAt(...);
关于java - JTable 行颜色取决于模型中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8137766/