JavaFX初探(盘状图表)
本章节介绍盘状图表,如下图所示:
创建盘状图表
为了创建一个盘状图表,最起码我们需要创建一个PieChart 对象,定义数据,关联数据和PieChart 对象,添加图表到应用中。当你定义数据的时候,需要定义你想要呈现数量的PieChart.Data对象。每一个PieChart.Data对象有两个域,:名称和值。
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.*;
import javafx.scene.Group;
public class PieChartSample extends Application {
@Override public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Imported Fruits");
stage.setWidth(500);
stage.setHeight(500);
ObservableList<PieChart.Data> pieChartData =
FXCollections.observableArrayList(
new PieChart.Data("Grapefruit", 13),
new PieChart.Data("Oranges", 25),
new PieChart.Data("Plums", 10),
new PieChart.Data("Pears", 22),
new PieChart.Data("Apples", 30));
final PieChart chart = new PieChart(pieChartData);
chart.setTitle("Imported Fruits");
((Group) scene.getRoot()).getChildren().add(chart);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
编译运行如下图所示:
设置图表和图例
chart.setLabelLineLength(10);
chart.setLegendSide(Side.LEFT);
我们也可以通过下面的设置来旋转这个图表:
chart.setClockwise(false);
chart.setStartAngle(90);
处理事件
final Label caption = new Label("");
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");
for (final PieChart.Data data : chart.getData()) {
data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
caption.setTranslateX(e.getSceneX());
caption.setTranslateY(e.getSceneY());
caption.setText(String.valueOf(data.getPieValue()) + "%");
}
});
}
编译运行如下图所示: