有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JTable中的java颜色渲染器是否为不可编辑字段?

我在JTable中有3列。一列是可编辑的。其他列不可编辑。可编辑列应显示为绿色,不可编辑列应显示为红色。我试过使用DefaultRenderer类,但它不起作用。如果有人知道这件事,请帮帮我


共 (1) 个答案

  1. # 1 楼答案

    有几种方法可以做到这一点。下面的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;
        }
    };
    

    或者您可以使用类重写DefaultTableCellRenderer,如下面的2

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