我想我在这里有一个奇怪的问题。这是我的代码:
private class BorderCellRenderer extends DefaultTableCellRenderer {
private Border extraBorder;
/**
* A cell render is based on labels which are changed to display the correct appearance
* This cell renderer adds extra border to every render action
*/
BorderCellRenderer(Border extraBorder) {
this.extraBorder = extraBorder;
}
/**
* The setBorder() is used to change the cell appearance.
* The trick is to override the call (of JComponent) and to add extra space
* to it by making it an compound border with.
*
* Remember that getBorder() now returns our compound border
*/
public void setBorder(Border border) {
super.setBorder(new CompoundBorder(border, extraBorder));
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
setFont(table.getFont());
setText(value.toString());
/* set color depending on the state of the row */
TableRowItem rowItem = ((FooModel) table.getModel()).getRow(row);
String state = rowItem.getState();
/* set tool tip on EMPLOYEE column */
if(column == FooModel.COL_EMPLOYEE) {
setToolTipText("blalba");
}
/* Paint text according to state*/
if(state.equals(RowItemState.ENTERED)) {
setForeground(Color.black);
//TODO setSelectionForeground(Color.black);
}
if(state.equals(RowItemState.SUBMITTED)) {
setForeground(Color.blue);
//TODO setSelectionForeground(Color.blue);
}
if(state.equals(RowItemState.APPROVED)) {
Color green = new Color(0, 128, 0); // greenish
setForeground(green);
//TODO setSelectionForeground(green);
}
if(state.equals(RowItemState.BOOKED)) {
setForeground(Color.red);
//TODO setSelectionForeground(Color.red);
}
switch (column) {
case FooModel.COL_EMPLOYEE:
case FooModel.COL_SAT:
case FooModel.COL_SUN:
if(state.equals(RowItemState.CHECKED)) {
setBackground(new Color(183, 244,176)); //light green
} else {
setBackground(java.awt.Color.lightGray);
}
break;
default:
if(state.equals(RowItemState.CHECKED)) {
setBackground(new Color(183, 244,176)); //light green
} else {
setBackground(java.awt.Color.white);
}
break;
}
//}
if (column == FooModel.COL_TOTAL){
if (table.getSelectedRowCount() > 0){
int rowsSelected[] = table.getSelectedRows();
double total = 0;
for (int j = 0; j < table.getSelectedRowCount(); j++){
Double dTemp = (Double) table.getValueAt(rowsSelected[j], FooModel.COL_TOTAL);
total += dTemp.doubleValue();
}
setToolTipText("Total Selected = " + String.valueOf(total));
}
}
// return super method for selections
return super.getTableCellRendererComponent(table, value,
isSelected, hasFocus,
row, column);
}
}
现在我们进入有趣的部分。此代码示例运行良好,但是当我取消注释 TODO 行以便setSelectionForeground()
调用方法时,我的 CPU 在四核上会达到 20%。这也发生在我所有同事的 PC 上(也是四核)。注释行时,CPU 大约为 0-1%。我觉得这很奇怪,无法弄清楚这里出了什么问题。我希望你能帮助我。