有 Java 编程相关的问题?

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

java根据JTable中的第一列值为特定行着色?

我试图根据JTable中的第一列值为特定行着色,但下面的代码根据行的索引为行着色。我的表只有四列。第一列有ID号。我需要根据这些ID号给行上色。例如,如果第一个ID为0,第二个ID也为0,则两者都应为“浅灰色”。有什么想法吗

table_1 = new JTable(){
    public Component prepareRenderer(TableCellRenderer renderer,int Index_row, int Index_col) {
        Component comp = super.prepareRenderer(renderer,Index_row, Index_col);
            //even index, selected or not selected
            if (Index_row % 2==0  &&  !isCellSelected(Index_row, Index_col)) {
                comp.setBackground(Color.lightGray);
            } else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };

下面是它现在的样子:

How it should look like


共 (1) 个答案

  1. # 1 楼答案

    渲染器正在根据传递给prepareRenderer()row参数选择颜色。谓词row % 2 == 0选择交替行进行着色,如图所示。您的问题意味着您实际上想要基于列0的值进行着色,ID。为此,您需要检查getValueAt(row, 0)的结果

    精确的公式取决于您的模型。使用此example,以下渲染器对以字母“T”开头的行进行着色

    private JTable table = new JTable(dataModel) {
    
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component comp = super.prepareRenderer(renderer, row, col);
            int modelRow = convertRowIndexToModel(row);
            if (((String) dataModel.getValueAt(modelRow, 0)).startsWith("T")
                && !isCellSelected(row, col)) {
                comp.setBackground(Color.lightGray);
            } else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };
    

    image

    附录:@mKorbel对启用排序时需要在模型视图坐标之间进行转换的问题进行了有益的评论,如here所述