jFreechart วิธีทำ Custom Label เพื่อแสดงผลบนกราฟดั่งใจเรา
วันนี้จะมานำเสนอ เทคนิค การใช้ jfreechart
ในการแสดงผลกราฟให้ได้ดั่งใจกับการทำCustom Label ให้กับ Pie Chart
ปรกติการ ทำ Data Set ใส่ให้กับ jfreechart เราจะใส่ไปแบบ
key กับ value เช่น
Value1 = 100
Value2 = 50
Value3 = 80
Value4 = 50
เวลาที่ jfreechart แสดงผลกราฟ โดย defult แล้ว
จะใช้ Key เป็น Label แล้วตามด้วย Value
แล้วถ้าเกิดว่าเราอยากจะทำอะไรเพิ่มเติม เช่น จะตกแต่ง
จะจัด format Value ให้แสดงอีกแบบ เราควรจะทำอย่างไร
วิธีการคือให้ทำ CustomLabelGenerator ขึ้นมาครับ โดยการ
implement interface นี้ PieSectionLabelGenerator
ตัวอย่างเช่น เราต้องการซ่อนตรง Value แล้วใช้ Key หรือ Label แสดงแทน
ก็ง่ายๆ ตามนี้เลย
static class CustomLabelGenerator implements PieSectionLabelGenerator {
public String generateSectionLabel(final PieDataset dataset, final Comparable key) {
String result = null;
if (dataset != null) {
result = key.toString();
}
return result;
}
}
แล้วตอนที่เราเรียกใช้ให้ Set ตัว Generator นี้เข้าไปในขึ้นตอนของการ plot
final PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
plot.setNoDataMessage("No data to display");
plot.setLabelGenerator(new CustomLabelGenerator());
เพียงเท่านี้ก็เรียบร้อย