データが無い時の表示文字列(setNoDataMessage)

広告

グラフのデータが存在しない時にグラフに文字列を設定することが出来ます。データが無いときの表示文字列を設定するにはPlotクラスで用意されている「setNoDataMessage」メソッドを使います。

Sets the message that is displayed when the dataset is empty or null, 
and sends a PlotChangeEvent to all registered listeners.

Parameters:
  message - the message (null permitted).

引数には表示する文字列を指定して下さい。

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

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

Plot plot = chart.getPlot();
plot.setNoDataMessage("データがありません");

サンプルプログラム

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

Test13_1.java

import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.plot.PlotOrientation;

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

import org.jfree.chart.plot.Plot;

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

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

  Test13_1(){
    JFreeChart chart = 
      ChartFactory.createBarChart("月別売上",
                                  "月",
                                  "売上",
                                  createData(),
                                  PlotOrientation.VERTICAL,
                                  true,
                                  false,
                                  false);

    Plot plot = chart.getPlot();
    plot.setNoDataMessage("データがありません");

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

  private DefaultCategoryDataset createData(){
    DefaultCategoryDataset data = new DefaultCategoryDataset();

    return data;
  }
}

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

データが無い時の表示文字列(setNoDataMessage)

( Written by Tatsuo Ikura )