简体   繁体   English

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

[英]How can I alternate the row color in an already created JTable?

I know how to alternate row color with this code:我知道如何使用此代码交替行颜色:

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

Now I want to change alternate row color in execution time, (eg click in a button and change alternate row color from Yellow to Gray).现在我想在执行时更改备用行颜色(例如,单击按钮并将备用行颜色从黄色更改为灰色)。

How I can do it?我该怎么做?

Make your JTable a full class (instead of an anonymous class as you have in your question), then create a method to do the toggling.使您的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;
    }
  }
}

Then, in your actionListener , just do然后,在您的actionListener ,只需执行

public void actionPerformed(ActionEvent e) { 
  myAlternatingJTable.toggleAlternateColor();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM