java - 如何在更改单元格值后渲染单元格颜色Jtable

标签 java swing jtable tablecellrenderer

我有一个 Jtable,其中包含一些值 [全部都是字符串]。有些值前面有“*”,我需要对其进行着色。我可以使用单元格渲染器为那些带有“*”的单元格着色。但是在给单元格着色后,我需要删除“*”而不改变单元格颜色。当我尝试编辑单元格值时,颜色变回白色。我在这里缺少什么。 这是代码

public SimpleTable()
{   
    JPanel panel = new JPanel();

    setTitle("Colored JTable");
    setBounds(400, 400, 400, 250);
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

    JTable table = new JTable(this.getRows(), this.getHeaders());
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);        
    table.setDefaultRenderer(Object.class, new MyTableRenderer());      

    this.scrollPane = new JScrollPane(table);
    panel.add(scrollPane);
    getContentPane().add(panel);
}

这是我的单元格渲染器

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
 Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if(table.getValueAt(row, column).toString().contains("*"))
            {               
                String v = table.getValueAt(row, column).toString().replace("*", "");               
                table.setValueAt(v, row, column);   
                cellComponent.setBackground(Color.YELLOW);              
            }
            else 
            {
                cellComponent.setBackground(Color.WHITE);                   
            }   
        return cellComponent;

最佳答案

选项:

  1. 将 * 保留在单元格数据中,将其用作绘画标记,但不要在渲染器中渲染它。
  2. 使用行的单独非可视化字段(例如 boolean 值)来确定单元格是否应涂成红色。

我更喜欢后者,因为它是一种更干净、更面向对象的解决方案。请注意,您的单元格渲染器应该参与渲染。它永远不应该更改表所保存的数据。

第一个示例:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(value != null && value.toString().contains("*")) {               
        value = value.toString().replace("*", "");               
        setBackground(Color.YELLOW);              
    } else {
        setBackground(Color.WHITE);                   
    }   
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

关于java - 如何在更改单元格值后渲染单元格颜色Jtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259106/

相关文章:

java - 在JTable中动态加载大量数据

java - 将控制台日志添加到 allure 报告中的每个步骤?(Java、Selenium、TestNG、Cucumber)

java - 为什么遵循控制结构条件的声明需要在 block 中?

Java:无符号字节到 int 的转换工作完美,除了 129 (0x81) 之外

java - Swing 组件出现问题

java - 两个JFrame的问题

java - 为什么 "@PathVariable"无法在 Spring Boot 中的接口(interface)上工作

java - 使用 GridBagLayout 出现不良结果

java - 使用 TransferHandler 拖放 JTable

java - JTable 中的类型错误