我知道如何使用此代码替换行颜色:
JTable table = new JTable(){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
Component returnComp = super.prepareRenderer(renderer, row, column);
Color alternateColor = Color.YELLOW;
Color whiteColor = Color.WHITE;
if (!returnComp.getBackground().equals(getSelectionBackground())){
Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
returnComp .setBackground(bg);
bg = null;
}
return returnComp;
};
现在我想在执行时更改备用行颜色(例如,单击按钮并将备用行颜色从黄色更改为灰色)。
我怎么做?
答案 0 :(得分:1)
让你的JTable
成为一个完整的课程(而不是你问题中的匿名课程),然后创建一个方法来进行切换。
public class AlternatingJTable extends JTable {
private static final Color ALTERNATE_ONE = Color.YELLOW;
private static final Color ALTERNATE_TWO = Color.GRAY;
private Color alternateColor = ALTERNATE_ONE;
private Color whiteColor = Color.WHITE;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
Component returnComp = super.prepareRenderer(renderer, row, column);
if (!returnComp.getBackground().equals(getSelectionBackground())){
Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
returnComp .setBackground(bg);
bg = null;
}
return returnComp;
};
public void toggleAlternateColor() {
if(this.alternateColor == ALTERNATE_ONE) {
this.alternateColor = ALTERNATE_TWO;
} else {
this.alternateColor = ALTERNATE_ONE;
}
}
}
然后,在actionListener
中,只需执行
public void actionPerformed(ActionEvent e) {
myAlternatingJTable.toggleAlternateColor();
}