【问题标题】:Changing color of cell in JTable更改 JTable 中单元格的颜色
【发布时间】:2011-08-14 20:53:20
【问题描述】:

我想更改 JTable 中单元格的颜色。我编写了自己的扩展 DefaultTableCellRenderer 的类。但是,我的班级的行为确实不一致。它所做的只是如果一个条目在列中出现两次,则将其标记为红色。这是我得到的结果:

请注意,在此类中,我还设置了特定列的字体。这很好用。我想知道为什么在尝试简单地设置颜色时会出现这种行为。

这是我的课:

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package inter2; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.util.List; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; /** * Used to display different fonts for different cells in the table */ public class CustomCellRenderer extends DefaultTableCellRenderer { private final int TRANSLATION_COL = 1; private final int VARIABLE_COL = 2; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); //set it so it can display unicode characters if (column == TRANSLATION_COL) { cell.setFont(new Font("MS Mincho",Font.PLAIN, 12)); } //marks a cell red if it is a duplicate variable name if(column == VARIABLE_COL) { MyTable theTable = (MyTable)table; String cellValue = theTable.getValueforCell(row, column); boolean dup = false; String[] columnData = theTable.getColumnData(column); //check if this is already in the list for(int i =0; i &lt columnData.length; i++) { String currTableValue = columnData[i]; if(currTableValue.equals(cellValue) && i != row) { dup = true; break; } } //we found a dup if(dup == true) { cell.setBackground(Color.red); } } return cell; } }

【问题讨论】:

    标签: java swing jtable


    【解决方案1】:

    DefaultTableCellRenderer 是一个特别糟糕的实现——你发现它是臭名昭著的“颜色记忆”。要解决此问题,您必须设置其颜色属性总是

    if (myCondition) 
        comp.setBackground(red)
    else 
        comp.setBackground(normal)
    

    或者更好(当然是偏袒我):在 SwingX 中使用 JXTable,它提供了对装饰单元格渲染器的完全可插拔支持,不仅在表格中,而且在组合框、树、列表中始终如一。

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2011-11-03
      • 2014-08-24
      • 2018-08-20
      • 2011-09-24
      • 1970-01-01
      • 2020-08-25
      • 2013-02-23
      • 2011-08-13
      相关资源
      最近更新 更多