我无法设置用户在运行时动态添加的行上jchooser的颜色... 渲染器不是为行着色而是为整个表着色....
insideAdd1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color initialColor = Color.red;
Color colorOfRow = JColorChooser.showDialog(table, "Title You Want", initialColor);
Map<Integer, Color> map = new HashMap<>();
map.put(rowClicked,colorOfRow );
table.setDefaultRenderer(Object.class,new DefaultTableCellRenderer()
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(map.containsValue(colorOfRow))
{setOpaque(true);
comp.setBackground(map.get(rowClicked));
table.repaint();
}
return comp;
}
});
为了避免这种情况,我试图使用另一种方法,但仍然无法为行着色,而是最终再次着色整个表格.....
table.getColumnModel().getColumn(0)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
table.getColumnModel().getColumn(1)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
table.getColumnModel().getColumn(2)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
table.getColumnModel().getColumn(3)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
table.getColumnModel().getColumn(4)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
table.getColumnModel().getColumn(5)
.setCellRenderer(new
MyrowCustomRender(rowClicked, colorOfRow));
对于上述情况,我使用以下渲染器类
class MyrowCustomRender extends DefaultTableCellRenderer {
int rowToColor;
Color colorToSet;
public MyrowCustomRender(int row,Color color) {
rowToColor=row;
colorToSet=color;
System.out.println(rowToColor);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
setOpaque(true);
if(rowToColor==row)
{
setBackground(colorToSet);
table.repaint();
}
else {
setBackground(table.getBackground());
table.repaint();
}
return comp;
}