PieChart_MousePressed1
Scope of this document :
  • annotations, Lambda Expressions
    • Lambda Expression
      chart.getData().stream().forEach((data) -> {
      data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
      e ->
  • PieChart and Muose Events
    import javafx.scene.input.MouseEvent;
  • Label
    final Label caption = new Label(" Year 2010 ");
  • Node:
Snapshot:: screens from NetBean JavaFx:
  • Supporting Libraries in NetBean 8.0
  • Stage and Scene Class ::

     
Code :

package javafxtemplate1;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFXTemplate1 extends Application {
@Override
public void start(Stage stage) {
Pane root = new Pane();
Scene scene = new Scene(root);
stage.setTitle("Demographic Chart");
stage.setWidth(500); stage.setHeight(500);
ObservableList<PieChart.Data> pieChartData =
FXCollections.observableArrayList(
new PieChart.Data("African-American", 32.9),
new PieChart.Data("Hispanic", 28.9),
new PieChart.Data("White",31.37 ),
new PieChart.Data("Asian",5.5 ));
final PieChart chart = new PieChart(pieChartData);
chart.setTitle("2010 Demographic Chart");
final Label caption = new Label(" Year 2010 ");
caption.setTextFill(Color.BLACK);
caption.setStyle("-fx-font: 24 arial;");
//
chart.getData().stream().forEach((data) -> {
data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
e -> {
double total = 0;
total = chart.getData().stream()
.map((d) -> d.getPieValue())
.reduce(total, (accumulator, _item) -> accumulator + _item);
caption.setTranslateX(e.getSceneX());
caption.setTranslateY(e.getSceneY());
String text = String.format
("%.1f%%", 100*data.getPieValue()/total) ;
caption.setText(text);
}
);
});

root.getChildren().addAll(chart, caption);
stage.setScene(scene);
stage.show();
}
// main window to launch stage
public static void main(String[] args) {
launch(args);
}
}
 

JavaFX PieChart:: MousePressed Event display