代码之家  ›  专栏  ›  技术社区  ›  Wt Riker

GetTableCellRenderComponent参数:JComboBox的“Value”和“IsSelected”

  •  0
  • Wt Riker  · 技术社区  · 7 年前

    我在JTable中有一个JComboBox,正在查看解释参数的getTableCellRendererComponent文档。

    table - the JTable that is asking the renderer to draw; can be null
    value - the value of the cell to be rendered. It is up to the specific renderer to interpret and draw the value. For example, if value is the string "true", it could be rendered as a string or it could be rendered as a check box that is checked. null is a valid value
    isSelected - true if the cell is to be rendered with the selection highlighted; otherwise false
    hasFocus - if true, render cell appropriately. For example, put a special border on the cell, if the cell can be edited, render in the color used to indicate editing
    row - the row index of the cell being drawn. When drawing the header, the value of row is -1
    column - the column index of the cell being drawn
    

    我的困惑是“价值”和“isSelected”。如果要呈现“值”,那么“isSelected”怎么可能是假的?如果为false,由于未选择“值”,为什么要呈现“值”?将呈现什么?TIA。

    camickr澄清和一些实验后更新

    显然,我只是部分了解正在发生的事情,这给我带来了一个问题。选择JComboBox时,“value”的内容是所选项目,而不是JComboBox实例。因此,我不再需要渲染JComboBox的实例。我也没有看到“table”的方法可以让我获取当前单元格中的组件。如何获取JComboBox实例,以便在该单元格中正确渲染长方体?当进行选择时,JComboBox将消失,我得到了案例2、5、6、7的运行时错误,这很有意义,因为值现在是字符串,而不是JComboBox实例。TIA。

    public class TimelineCellRenderer implements TableCellRenderer {
    
    @SuppressWarnings("unchecked")
    @Override
    public Component getTableCellRendererComponent(JTable table_, Object value_, boolean isSelected_, boolean hasFocus_, int row_,int column_) {
    
        Component field=null;
        String str="";
        if (value_!=null) {
            str=value_.toString();
        }
        switch (column_) {
            case 0:
            case 3:
            case 4:
            case 8:
                field=new JTextField();
                ((JTextField) field).setText(str);
                break;
            case 1:
                field=new JTextField();
                ((JTextField) field).setText(Double.toString((Double) value_));
                break;
            case 2:
            case 5:
            case 6:
            case 7:
                field=(JComboBox<String>) value_;
                break;
            case 9:
                field=new JTextField();
                ((JTextField) field).setText("Add button");
                break;
            case 10:
                field=new JTextField();
                ((JTextField) field).setText("del button");
                break;
        }
        if (field instanceof JTextField) {
            Font f=field.getFont().deriveFont(Font.PLAIN, (float) 14);
            field.setFont(f);
        }
        return(field);
    }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   camickr    7 年前

    每当单击单元格时,选定的行都会更改。

    因此,行中的每个单元格都需要渲染,因为行高亮显示需要更改。

    在该行中,一次只能选择一个单元格。

    此外,需要在不高亮显示的情况下重新绘制先前选定行的所有单元格。

    因此,基本答案是,该方法被多次调用,每个单元格调用一次,参数将不同。