Processing Events for a Pie Chart — КиберПедия 

Двойное оплодотворение у цветковых растений: Оплодотворение - это процесс слияния мужской и женской половых клеток с образованием зиготы...

Опора деревянной одностоечной и способы укрепление угловых опор: Опоры ВЛ - конструкции, предназначен­ные для поддерживания проводов на необходимой высоте над землей, водой...

Processing Events for a Pie Chart

2022-10-10 101
Processing Events for a Pie Chart 0.00 из 5.00 0 оценок
Заказать работу

Although a pie chart slice is not a Node object, each PieChart.Data element has a node associated with it, which can be used to analyze events and process them accordingly. The code fragment shown in Example 2-3 creates an EventHandler object to process a MOUSE_PRESSED event that falls into a particular chart slice.

Example 2-3 Processing Mouse Events for a Pie Chart 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()) + "%"); }    }); }  

When you add this code fragment to the application code and compile and run it, the application starts reacting to the mouse clicks. Figure 2-5 shows the value displayed for Pears when a user clicks the corresponding slice.

Figure 2-5 Processing the Mouse-Pressed Events for a Pie Chart

Description of "Figure 2-5 Processing the Mouse-Pressed Events for a Pie Chart"

By using this coding pattern, you can process various events or apply visual effects to the whole chart as well as to its slices.

Related API Documentation

  • PieChart
  • PieChart.Data
  • Chart

Line Chart

This chapter describes the line chart, a type of two-axis chart that presents data as a series of points connected by straight lines.

The line chart is often used to illustrate the dynamics of data over a particular interval of time. Figure 3-1 demonstrates a typical line chart with three series of data.

Figure 3-1 Example of a Line Chart

Description of "Figure 3-1 Example of a Line Chart"

Each two-axis chart has two axes, the plot of data points, and the legend. You can also specify a title for the chart.

Creating a Line Chart

To create a line chart, at a minimum, you must define two axes, create the LineChart object by instantiating the LineChart class, create one or more series of data by using the XYChart.Series class, and assign the data to the chart. Example 3-1 implements these tasks.

Example 3-1 SimpleLineChart importjavafx.application.Application; importjavafx.scene.Scene; importjavafx.scene.chart.LineChart; importjavafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.stage.Stage;     public class LineChartSample extends Application {   @Override public void start(Stage stage) {    stage.setTitle("Line Chart Sample");    //defining the axes    final NumberAxis xAxis = new NumberAxis();    final NumberAxis yAxis = new NumberAxis();    xAxis.setLabel("Number of Month");    //creating the chart    final LineChart<Number,Number> lineChart =            new LineChart<Number,Number>(xAxis,yAxis);      lineChart.setTitle("Stock Monitoring, 2010");    //defining a series    XYChart.Series series = new XYChart.Series();    series.setName("My portfolio");    //populating the series with data    series.getData().add(new XYChart.Data(1, 23));    series.getData().add(new XYChart.Data(2, 14));    series.getData().add(new XYChart.Data(3, 15));    series.getData().add(new XYChart.Data(4, 24));    series.getData().add(new XYChart.Data(5, 34));    series.getData().add(new XYChart.Data(6, 36));    series.getData().add(new XYChart.Data(7, 22));    series.getData().add(new XYChart.Data(8, 45));    series.getData().add(new XYChart.Data(9, 43));    series.getData().add(new XYChart.Data(10, 17));    series.getData().add(new XYChart.Data(11, 29));    series.getData().add(new XYChart.Data(12, 25));      Scene scene = new Scene(lineChart,800,600);    lineChart.getData().add(series);      stage.setScene(scene);    stage.show(); }   public static void main(String[] args) { launch(args); } }

In this example, both vertical and horizontal axes are created by using the NumberAxis class, a subclass of the Axis class, to represent numerical values. Having declared both X and Y axes numerical, you should specify Number parameters for XYChart.Data objects when creating a series of data. The first parameters of XYChart.Data objects define values for the horizontal axis, whereas, the second parameters of the XYChart.Data objects define values for the vertical axis.

The result of compiling and running this application is shown in Figure 3-2.


Поделиться с друзьями:

Археология об основании Рима: Новые раскопки проясняют и такой острый дискуссионный вопрос, как дата самого возникновения Рима...

Архитектура электронного правительства: Единая архитектура – это методологический подход при создании системы управления государства, который строится...

Биохимия спиртового брожения: Основу технологии получения пива составляет спиртовое брожение, - при котором сахар превращается...

История создания датчика движения: Первый прибор для обнаружения движения был изобретен немецким физиком Генрихом Герцем...



© cyberpedia.su 2017-2024 - Не является автором материалов. Исключительное право сохранено за автором текста.
Если вы не хотите, чтобы данный материал был у нас на сайте, перейдите по ссылке: Нарушение авторских прав. Мы поможем в написании вашей работы!

0.009 с.