我有JTable
,我希望表中的结果根据属性的特定值着色;这里comp
为null
:
private JNI18NTable _issueIncidentTable = new JNI18NTable(I18N_ID, COLUMNS, "issue.table.") {
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
int RangeIndex = Utilities.rowIndexToRangeIndex(_resultIter, row);
Row theRow = _resultIter.getRowAtRangeIndex(RangeIndex);
System.out.println("the row is" + theRow.getAttribute("Type"));
boolean markRow = theRow != null && theRow.getAttribute("Type").toString().equals("c");
boolean isSelected = isRowSelected(row);
System.out.println("the comp" + comp);
if (markRow) {
comp.setForeground(Color.white);
comp.setBackground(isRowSelected(row) ? Color.red.darker() : Color.red);
} else {
comp.setForeground(isSelected ? getSelectionForeground() : getForeground());
comp.setBackground(isSelected ? getSelectionBackground() : getBackground());
}
return comp;
}
};
答案 0 :(得分:2)
推断sscce,prepareRenderer()
的实施似乎如下所示。您可能会在代码中的其他位置查找假定的问题。特别是,Utilities.rowIndexToRangeIndex()
的实现应该使用表自己的 convert 方法。此外,始终使用isSelected
的值。
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
/**
* @see http://stackoverflow.com/a/20684058/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
JTable table = new JTable(new DefaultTableModel(10, 1) {
@Override
public Object getValueAt(int row, int col) {
return "Row " + row;
}
}) {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
boolean isSelected = isRowSelected(row);
if (row % 2 == 0) {
comp.setForeground(Color.white);
comp.setBackground(isSelected ? Color.red.darker() : Color.red);
} else {
comp.setForeground(isSelected ? getSelectionForeground() : getForeground());
comp.setBackground(isSelected ? getSelectionBackground() : getBackground());
}
return comp;
}
};
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Test().display();
}
});
}
}