Swing JTable - 突出显示与所选行的其余部分不同颜色的选定单元格? [英] Swing JTable - Highlight selected cell in a different color from rest of the selected row?

查看:177
本文介绍了Swing JTable - 突出显示与所选行的其余部分不同颜色的选定单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的摆动JTable,要求是当点击任何单元格时,整个行应该突出显示,并且单击的单元格应该与突出显示的行的其余部分颜色不同。

I have a basic swing JTable and the requirement is that when clicked on any cell, the entire row should be highlighted, and also that the cell which was clicked should be a different color from the rest of the highlighted row.

目前, isRowSelectionAllowed true

I尝试使用自定义 TableCellRenderer ,如下所示:

I tried using a custom TableCellRenderer which is as follows:

public class CustomTableCellRenderer extends DefaultTableCellRenderer
{

public static final DefaultTableCellRenderer    DEFAULT_RENDERER    = new DefaultTableCellRenderer();
    @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    if (isSelected) {
        c.setBackground(Color.red);
    }
    else {
        c.setForeground(Color.black);
        c.setBackground(Color.white);
    }
    return c;   
  }     
}

但这似乎不起作用(整行是用红色突出显示。

But that did not seem to work (entire row was highlighted in red).

我还尝试按如下方式设置UIManager属性:

I also tried setting the UIManager property as follows:

UIManager.put("Table.focusCellBackground", 
         new javax.swing.plaf.ColorUIResource (Color.red));

但这似乎也不起作用(即使我尝试使用

But that does not seem to work either (even though, when I tried setting a border using

UIManager.put("Table.focusCellHighlightBorder", 
         new BorderUIResource.LineBorderUIResource(Color.red)); 

运作良好)

你能不能给任何建议我可能需要做什么?

Could you please give any suggestions what I might need to do?

推荐答案

试试这个:

jtable.setCellSelectionEnabled(true);

然后在 getTableCellRendererComponent

if (table.isCellSelected(row, column))
    setForeground(Color.red);
else if (table.isRowSelected(row))
    setForeground(Color.green);
else if (table.isColumnSelected(column))
    setForeground(Color.blue);
else
    setForeground(Color.black);

这将使所选单元格呈现红色,其余部分呈绿色,其余部分为蓝色的列。注意:单元格选择要求选择模型为单一,其他选择模型可能会导致不可预测的行为。

That will render the selected cell in red, the rest of the row in green, and the rest of the column in blue. Note: cell selection requires the selection model be single, other selection models may cause unpredictable behaviors.

这篇关于Swing JTable - 突出显示与所选行的其余部分不同颜色的选定单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆