简体   繁体   English

JTable中的Color Renderer是否为不可编辑字段?

[英]Color Renderer in JTable if it is non editable field?

I have 3 columns in JTable. 我在JTable中有3列。 One column is editable. 一栏是可编辑的。 Other columns are non-editable. 其他列不可编辑。 Editable column should be displayed green color and non-editable column should be in red color. 可编辑列应显示为绿色,不可编辑列应显示为红色。 I have tried with DefaultRenderer class but its not working. 我已经尝试过DefaultRenderer类,但是它不起作用。 Please if anyone know this, help me. 如果有人知道,请帮助我。

Well there are few ways to do this. 好吧,有几种方法可以做到这一点。 Following 1 will render the column 1 as grey. 接下来的1将使列1呈现为灰色。

JTable table = new JTable() {
    public Component prepareRenderer(TableCellRenderer renderer,
                                     int rowIndex, int vColIndex) {
        Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
        if (vColIndex == 0) {//if first column
            c.setBackground(Color.red);
        } else {
            c.setBackground(Color.green);
        }
        return c;
    }
};

Or you can have class override DefaultTableCellRenderer like following 2 或者,您也可以像下面的2那样覆盖Class DefaultTableCellRenderer

public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
    public Component getTableCellRendererComponent (JTable table, Object obj, 
                         boolean isSelected, boolean hasFocus, int row, int column){
        Component cell = super.getTableCellRendererComponent(table, obj, 
                            isSelected, hasFocus, row, column);

        if (column == 0){
            cell.setBackground(Color.red);
        }
        else{
            cell.setBackground(Color.green);
        }
        return cell;
    }
}

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

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