背景色の設定(setBackgroundPaint)

広告

タイトルの背景色を設定する方法を確認します。TextTitleクラスで用意されている「setBackgroundPaint」メソッドを使います。

Sets the background paint and sends a TitleChangeEvent to all registered 
listeners. If you set this attribute to null, no background is painted 
(which makes the title background transparent).

Parameters:
  paint - the background paint (null permitted).

引数にはPaintインターフェースを実装したクラスのオブジェクトを指定します。Paintインターフェースを実装している主なクラスは以下の通りです。

クラス使用方法
Color単純色
GradientPaint線形グラデーションパターン
TexturePaintテクスチャーによる塗りつぶし
LinearGradientPaint線形グラデーションパターン
RadialGradientPaint円放射状グラデーションパターン

今回はColorクラスを使って文字の色を設定してみます。Colorクラスについての詳細は「Colorクラス」を参照して下さい。

例えば次のように記述します。

JFreeChart chart = ChartFactory.createPieChart(...);   # 引数は省略

TextTitle title = new TextTitle("タイトル");
title.setBackgroundPaint(Color.BLUE);

chart.setTitle(title);

サンプルプログラム

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

Test6_1.java

import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.data.general.DefaultPieDataset;

import javax.swing.JFrame;
import java.awt.BorderLayout;
import org.jfree.chart.ChartPanel;

import org.jfree.chart.title.TextTitle;
import java.awt.Font;
import java.awt.Color;

public class Test6_1 extends JFrame{
  public static void main(String[] args) {
    Test6_1 frame = new Test6_1();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 500, 500);
    frame.setTitle("グラフサンプル");
    frame.setVisible(true);
  }

  Test6_1(){
    JFreeChart chart = 
      ChartFactory.createPieChart("",
                                   createData(),
                                   true,
                                   false,
                                   false);

    TextTitle title = new TextTitle("夏の旅行");
    title.setFont(new Font("MS 明朝", Font.BOLD | Font.ITALIC, 38));
    title.setBackgroundPaint(Color.RED);

    chart.setTitle(title);

    ChartPanel cpanel = new ChartPanel(chart);
    getContentPane().add(cpanel, BorderLayout.CENTER);
  }

  private DefaultPieDataset createData(){
    DefaultPieDataset data = new DefaultPieDataset();
    data.setValue("海外", 30);
    data.setValue("国内", 60);
    data.setValue("行かない", 8);
    data.setValue("未定", 2);

    return data;
  }
}

上記をコンパイルした後で実行すると次のようにJavaアプリケーションが起動します。

背景色の設定(setBackgroundPaint)

( Written by Tatsuo Ikura )