2

の最初の列の値に従って特定の行に色を付けようとしていますJTableが、以下のコードは行のインデックスに従って行に色を付けます。私のテーブルには 4 つの列しかありません。最初の列には ID 番号があります。これらの ID 番号に従って行に色を付ける必要があります。たとえば、最初の ID が 0 で 2 番目の ID も 0 の場合、両方とも「lightGray」にする必要があります。何かアイデアはありますか?

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

現在の外観は次のとおりです。

どのように見えるべきか

4

1 に答える 1

6

レンダラーは、 にrow渡されたパラメーターに基づいて色を選択していますprepareRenderer()。写真に示すように、述語row % 2 == 0はシェーディングのために交互の行を選択します。あなたの質問は、実際には列 0 の値に基づいてシェーディングを行いたいことを意味しますID。このためには、 の結果を調べる必要がありますgetValueAt(row, 0)

正確な配合はモデルによって異なります。このを使用して、次のレンダラーは文字「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;
    }
};

画像

補遺: @mKorbelは、ここで説明されているように、並べ替えが有効になっているときにモデルビューの座標を変換する必要があることについて有益なコメントをしています。

于 2012-12-29T00:47:12.153 に答える