2009-07-02 5 views

答えて

14

JListセルの外観をカスタマイズするには、ListCellRendererの独自の実装を作成する必要があります。

classのサンプル実装は次のように見えるかもしれ

:(ラフスケッチ、テストされていない)

public class MyListCellThing extends JLabel implements ListCellRenderer { 

    public MyListCellThing() { 
     setOpaque(true); 
    } 

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
     // Assumes the stuff in the list has a pretty toString 
     setText(value.toString()); 

     // based on the index you set the color. This produces the every other effect. 
     if (index % 2 == 0) setBackground(Color.RED); 
     else setBackground(Color.BLUE); 

     return this; 
    } 
} 

このレンダラーを使用するには、あなたのJListさんにコンストラクタは、このコードを置く:

setCellRenderer(new MyListCellThing()); 

選択したフォーカスに基づいてセルの動作を変更するには、指定されたブール値を使用します。

+0

行が選択されているケースを処理する必要があります(色が変わるとき) –

+0

ええ、私はその記事の一番下に記載しました。 – jjnguy

+0

マイナーニックピット:setBackgroundColorではなくsetBackgroundにする必要があります。 – ataylor

関連する問題