繁体   English   中英

更改单元格值Jtable后如何呈现单元格颜色

[英]how to render cell color after changing cell value Jtable

我有一个带有一些值的Jtable [全部都是字符串]。 有些值前面有“ *”,需要为它们上色。 我可以使用Cell Renderer为具有“ *”的那些单元着色。 但是,在为单元格着色之后,我需要在不更改单元格颜色的情况下删除“ *”。 当我尝试编辑单元格值时,颜色变回白色。 我在这里想念什么。 这是代码

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. 使用该行的单独的非可视化字段(例如布尔值)来确定是否应将单元格涂成红色。

我更喜欢后者作为更清洁的OOP解决方案。 请注意,您的单元格渲染器应与渲染有关。 它永远都不应更改表中保存的数据。

对于第一个示例:

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

暂无
暂无

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

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