【发布时间】:2011-10-17 13:20:11
【问题描述】:
我正在尝试设置 Swing Jtable 行的颜色。 我使用这个类来扩展 Jtable,正如网上建议的那样。
public class ColorTable extends JTable {
private static final long serialVersionUID = 1L;
private Map rowColor = new HashMap();
private Map columnColor = new HashMap();
private Color cellColor;
private Color defaultColor;
public ColorTable( TableModel model ) {
super( model );
}
public void setRowColor( int row, Color c) {
rowColor.put( new Integer( row ), c );
}
public void setColumnColor( int column, Color c ) {
columnColor.put( new Integer( column ), c );
}
public void setCellColor( Color c ) {
cellColor = c;
}
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
public Component prepareRenderer( TableCellRenderer renderer, int row, int column ) {
Component c = super.prepareRenderer( renderer, row, column );
if ( defaultColor == null )
defaultColor = c.getBackground();
// Color order is as follows:
// rowSelection, checkBox toggle for row color, column color, cell color
if ( ! isRowSelected( row ) ) {
Color color = (Color) rowColor.get( new Integer( row ) );
if ( color == null || Boolean.FALSE.equals( getModel().getValueAt( row, 0 ) ) )
color = (Color) columnColor.get( new Integer( column ) );
if ( color == null ) {
// cell color only if cell has special value, for example purposes,
// if the cell value begins with a 2
Object value = getValueAt( row, column );
if ( value != null && value.toString().startsWith( "2" ) )
color = cellColor;
}
if ( color != null )
c.setBackground( color );
else
c.setBackground( defaultColor );
}
return c;
}
public void resetColor(Color color) {
for(int i=0;i<this.getRowCount();i++)
this.setRowColor(i, color);
}
}
我只是简单地添加了resetColor(Color color)方法,以便用相同的颜色初始化所有行。
它在第一次使用时可以工作,但是当我想更改颜色时,我遇到了问题。例如,如果我在按钮动作侦听器中执行 sollowing 代码,我会在第一次迭代时正确地为表格着色,并且永远不会改变背景。
deployTable.resetColor(Color.green);
// set red background to the
for (Integer x : indexes) {
System.out.println("index "+x+" red!");
deployTable.setRowColor(x, Color.red);
}
deployTable.revalidate();
有人知道它是什么吗??
谢谢, 步骤
【问题讨论】:
-
我没有看到
repaint()。
标签: java swing colors jtable refresh