简体   繁体   English

在JTable中将颜色更改为未选定的行

[英]Change color to unselected row in JTable

I need to highlight the color of a selected row in a JTable. 我需要突出显示JTable中所选行的颜色。 I'm using my own CellRenderer for this, and it works, but when i select another row, the previous one still stays highlighted. 我正在使用我自己的CellRenderer,它可以工作,但当我选择另一行时,前一行仍然保持高亮显示。 The idea is to keep in blue color just the selected one, and keep in it's original color the other ones. 我们的想法是保持所选择的蓝色,并保持其他的原始颜色。 In adittion i'm making the pair columns: gray and the non pair: white, so this is the code at the CellRenderer 在adittion我正在制作对列:灰色和非对:白色,所以这是CellRenderer的代码

private class Renderer extends DefaultTableCellRenderer
{
    private static final long serialVersionUID = 1L;
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
                                         boolean isSelected, boolean hasFocus,
                                         int row, int column)
    {
        super.getTableCellRendererComponent(table, value, isSelected,
                                                          hasFocus, row, column);

        int columnIndex = table.getSelectedColumn();
        int rowIndex = table.getSelectedRow();

        if (columnIndex != -1 && rowIndex != -1){
            this.setBackground(Color.BLUE);
        } else {
            if (row % 2 == 0) this.setBackground(Color.decode("0xF9F9F9"));
            else this.setBackground(Color.decode("0xF1F1F1"));
        }
        return this;
    }
}

EDIT: F1F1F1 is a color nearly to white and F9F9F9F9 is kinda a light gray 编辑:F1F1F1颜色接近白色,F9F9F9F9有点浅灰色

You should add something like the code below before you return from the method: 在从方法返回之前,您应该添加类似下面的代码:

if (!isSelected) {
  setBackground(...);
}

If you do not mind using 3th party libs: the JXTable of the SwingX project has built-in support for alternating row colors using HighLighter s. 如果您不介意使用第三方库:SwingX项目的JXTable内置支持使用HighLighter交替行颜色。

I found an article which shows some screenshots of the result of applying a HighLighter to the JXTable . 我发现了一篇文章 ,其中显示了将HighLighter应用于JXTable的结果的一些截图。 Problem is that the article is not up-to-date. 问题是该文章不是最新的。 The functionality is still there but the code has changed. 功能仍然存在,但代码已更改。 While the article still mentions the AlternateRowHighligher as shown here 虽然文章仍然提到AlternateRowHighligher如此处所示

HighlighterPipeline highlighters = new HighlighterPipeline();
highlighters.addHighlighter(new AlternateRowHighlighter());
table.setHighlighters(highlighters);

the current approach would be more like 目前的做法更像是

JXTable table;
Highlighter alternateStriping = 
  HighlighterFactory.createAlternateStriping( Color.decode( "0xF9F9F9" ), 
                                              Color.decode( "0xF1F1F1" ) );
table.setHighlighters( alternateStriping );

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

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