- Home ›
- JFreeChartを使ったグラフ作成 ›
- 円グラフ(PieChart, PieChart3D) ›
- HERE
円グラフの描画領域(PiePlotクラス)
グラフの描画領域を取得し、描画領域に対する設定を行っていきます。ファクトリメソッドを使ってJFreeChartクラスのオブジェクトを作成した場合は、JFreeChartクラスで用意されている「getPlot」メソッドを使ってPlotクラスのオブジェクトを取得します。
getPlot public Plot getPlot()
Returns the plot for the chart. The plot is a class responsible for coordinating the visual representation of the data, including the axes (if any). Returns: The plot.
円グラフの場合には、取得したPlotクラスのオブジェクトを、PlotクラスのサブクラスであるPiePlotクラスにキャストして取得して使います。例えば次のように記述します。
JFreeChart chart = ChartFactory.createPieChart(...); /* 引数は省略 */ PiePlot plot = (PiePlot)chart.getPlot();
ではPiePlotクラスについて確認します。
PiePlotクラス
PiePlotクラスのクラス図は次のようになっています。
- java.lang.Object
- org.jfree.chart.plot.Plot
- org.jfree.chart.plot.PiePlot
- public class PiePlot extends Plot implements java.lang.Cloneable, java.io.Serializable
用意されているコンストラクタは次の2つです。
| コンストラクタ |
|---|
| PiePlot() Creates a new plot. |
| PiePlot(PieDataset dataset) Creates a plot that will draw a pie chart for the specified dataset. |
今回はコンストラクタでオブジェクトを直接生成するのではなく、JFreeChartクラスの「getPlot」メソッドでオブジェクトを取得します。
取得したPiePlotクラスのオブジェクトは円グラフの描画領域を表すオブジェクトです。PiePlotクラスで定義されているメソッドや、親クラスのPlotクラスで用意されているメソッドを使用して描画領域に対する設定を行うことが可能です。
サンプルプログラム
では簡単なサンプルを作成して試してみます。
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.plot.PiePlot;
import java.awt.Color;
public class Test4_1 extends JFrame{
public static void main(String[] args) {
Test4_1 frame = new Test4_1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(10, 10, 500, 500);
frame.setTitle("グラフサンプル");
frame.setVisible(true);
}
Test4_1(){
JFreeChart chart =
ChartFactory.createPieChart("夏の旅行",
createData(),
true,
false,
false);
PiePlot plot = (PiePlot)chart.getPlot();
plot.setBackgroundPaint(Color.ORANGE);
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アプリケーションが起動します。
今回は例として描画領域の背景色をオレンジに変更しました。また上記のオレンジの箇所がグラフの描画領域となります。
( Written by Tatsuo Ikura )
JavaDrive