我有這樣的代碼在我的表模型:JTable行顏色取決於模型中的值?
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));
表所示像往常一樣沒有黃色。爲什麼?
update2。
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;
}
};
表是空的:(
很可能你的渲染器沒有被使用 - 它是按列設置的,然後設置模型。通過默認列在setModel上重新創建(或接收一個structureChanged),從而失去所有配置 – kleopatra
謝謝指出。但是當我打電話給渲染器? – bunnyjesse112