如何在已创建的JTable中交替行颜色?

时间:2015-08-28 16:39:07

标签: java swing colors jtable

我知道如何使用此代码替换行颜色:

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;
};

现在我想在执行时更改备用行颜色(例如,单击按钮并将备用行颜色从黄色更改为灰色)。

我怎么做?

1 个答案:

答案 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();
}