我知道如何用以下代码替换行颜色:

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


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

我该怎么办?

最佳答案

使您的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();
}

07-24 09:38