1行毎に背景色を変更する

広告

ListCellRendererの応用として1行毎に背景色を変更する方法を確認します。

前頁で見たようにJComoboBoxクラスの登録するデータ自体に背景色の情報を持たせて、「getListCellRendererComponent」メソッド内で取り出して設定することも可能ですが、「getListCellRendererComponent」メソッドの3番目の引数に現在表示しようとしている項目のインデックスが渡されてきますのでその値を利用します。

具体的にはインデックス番号が偶数か奇数かを判断し、別々の背景色を設定するようにします。

class MyCellRenderer extends JLabel implements ListCellRenderer {
  public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus){

      String data = value.toString();
      setText(data);

      if (isSelected){
        setForeground(Color.white);
        setBackground(Color.black);
      }else{
        setForeground(Color.black);

        if (index % 2 == 0){
          setBackground(Color.white);
        }else{
          setBackground(new Color(238, 232, 170));
        }
      }

    return this;
  }
}

このようにすることで、JComboBoxクラスに登録されるデータは気にすることなく1行毎に背景色を変更して設定することが可能となります。

サンプルプログラム

では簡単なサンプルを作成して試してみます。

JComboBoxTest19.java

import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.Component;

public class JComboBoxTest19 extends JFrame{

  public static void main(String[] args){
    JComboBoxTest19 frame = new JComboBoxTest19();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 300, 200);
    frame.setTitle("タイトル");
    frame.setVisible(true);
  }

  JComboBoxTest19(){
    String[] combodata = {"08:00","09:00","10:00","11:00",
                          "12:00","13:00","14:00","15:00",
                          "16:00","17:00","18:00","19:00"};

    DefaultComboBoxModel model = new DefaultComboBoxModel(combodata);

    JComboBox combo = new JComboBox(model);
    combo.setPreferredSize(new Dimension(140, 30));

    MyCellRenderer renderer = new MyCellRenderer();
    combo.setRenderer(renderer);

    JPanel p = new JPanel();
    p.add(combo);

    getContentPane().add(p, BorderLayout.CENTER);
  }

  class MyCellRenderer extends JLabel implements ListCellRenderer{

    MyCellRenderer(){
      setOpaque(true);
    }

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus){

      String data = value.toString();
      setText(data);

      if (isSelected){
        setForeground(Color.white);
        setBackground(Color.black);
      }else{
        setForeground(Color.black);

        if (index % 2 == 0){
          setBackground(Color.white);
        }else{
          setBackground(new Color(238, 232, 170));
        }
      }

      return this;
    }
  }
}

上記をコンパイルした後で実行すると次のように表示されます。

JComboBoxで1行毎に背景色を変更する

JComboBoxで1行毎に背景色を変更する

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。