繁体   English   中英

Swing JTable - 以与所选行的其余部分不同的颜色突出显示所选单元格?

[英]Swing JTable - Highlight selected cell in a different color from rest of the selected row?

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

目前,我已将isRowSelectionAllowed视为true

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

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

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

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

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

但这似乎也不起作用(即使我尝试使用边框设置边框时)

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

效果很好)

你能否提出我可能需要做的建议?

试试这个:

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

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

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

您需要检查“hasFocus”变量,而不是“isSelected”变量。

另一个选项是使用Table Row Renderering方法,而不是创建多个自定义渲染器(如果您的表具有不同类类型的列)。

您需要关闭行选择并为表格选择单元格。 然后找到一种方法返回并在需要时突出显示该行。

暂无
暂无

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

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