bun*_*112 3 java swing jtable colors
我在Table模型中有这个代码:
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
Run Code Online (Sandbox Code Playgroud)
我想更改每一行的背景颜色,例如,如果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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用渲染器:
int vColIndex = 0;
TableColumn col = resultTable.getColumnModel().getColumn(vColIndex);
col.setCellRenderer(new MyTableCellRenderer());
resultTable.setModel(new DocumentProjectTableModel(docs));
Run Code Online (Sandbox Code Playgroud)
表格像往常一样没有黄色.为什么?
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;
}
};
Run Code Online (Sandbox Code Playgroud)
表是空的:(
由于您希望为整行着色,因此更容易使用表行渲染,而不是创建多个自定义渲染器.
我找到了根据JTable中的值重新着色行的示例.但getIsValid和getIsRegistered()实际上并未显示,它们仅存在于模型中
您仍然可以从表中访问该模型.你只需使用:
table.getModel().getValueAt(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14434 次 |
| 最近记录: |