tutorial que ejemplos java javafx charts javafx-2 javafx-8

que - javafx tutorial pdf



JavaFX: ¿Cómo deserializar dinámicamente crear Series de Cartas de Área? (1)

Hay varias formas de lograr esto. Algunos son más rápidos que otros. Te mostraré una manera simple en que se puede hacer, pero ten en cuenta que hay varias.

Si la velocidad no es una preocupación, me gusta serializar objetos en el texto de base64. Esto hace que sea muy fácil moverse y almacenar en DB''s como texto. Si estaba trabajando en un proyecto que requería mover una gran cantidad de datos, una velocidad importante, entonces podría no seguir este enfoque.

1) Use la serialización de Java para serializar el objeto en un byte[] .

protected byte[] convertToBytes(Object object) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(object); return bos.toByteArray(); } } protected Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException { try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { return in.readObject(); } }

Estos métodos se pueden usar para convertir objetos Java para convertir objetos dentro y fuera de byte [].

2) Tome el byte [] del paso 1 y úselo para serializar en texto base64. Estos dos métodos convertirán su seriesContainer en base64 String, o convertirán una base64 String en seriesContainer .

public String toBase64() { try { return Base64.getEncoder().encodeToString(convertToBytes(seriesContainer)); } catch (IOException ex) { throw new RuntimeException("Got exception while converting to bytes.", ex); } } public void initializeFromBase64(String b64) { byte[] bytes = Base64.getDecoder().decode(b64); try { this.seriesContainer = (LinkedList<XYChart.Series<Number, Number>>) convertFromBytes(bytes); } catch (Exception ex) { throw new RuntimeException("Got exception while converting from bytes.", ex); } }

3) Tome el String del paso 2 y póngalo en un DB, o léalo desde un DB.

Estoy agregando series dinámicamente usando la lista en la Tabla de áreas. Quiero desenvolver la serie. Lo necesito porque quiero guardar los datos de la serie Area Chart en db.

Cuando la aplicación se ejecuta es así:

El usuario puede agregar series completando los campos de texto y haciendo clic en el botón Agregar:

Lo que quiero es que cuando el usuario haga clic en el botón Guardar, traduzca las series ya agregadas a los datos para poder almacenarlos en db. Pero lo que probé no me da los datos precisos. De acuerdo con las series sobre chat, quiero obtener resultados como este:

Series 0 Employees: 5 Series 0 Start: 1 Series 0 End: 7 Series 1 Employees: 3 Series 1 Start: 9 Series 1 End: 12

Pero estoy obteniendo esto:

Series 0 Employees: 5 Series 0 Start: 1 Series 0 End: 5 Series 1 Employees: 3 Series 1 Start: 10 Series 1 End: 5

Código:

import java.net.URL; import java.util.LinkedList; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.chart.AreaChart; import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart.Series; import javafx.scene.control.TextField; /** * * @author blj0011 */ public class SampleController implements Initializable { @FXML private AreaChart<Number, Number> areaChart; @FXML private TextField txtSt; @FXML private TextField txtEt; @FXML private TextField txtNb; LinkedList<XYChart.Series<Number, Number>> seriesContainer = new LinkedList<Series<Number, Number>>(); //Button add functionality @FXML private void generateGraph() { Double start = Double.parseDouble(txtSt.getText()); Double end = Double.parseDouble(txtEt.getText()); double numberEmployees = Integer.parseInt(txtNb.getText()); XYChart.Series<Number, Number> series= new XYChart.Series<>(); for (int i = start.intValue(); i <= end.intValue(); i++) { series.getData().add(new XYChart.Data(i, numberEmployees)); } // Add Series to series container. seriesContainer.add(series); //Add only new series to AreaChart for(XYChart.Series<Number, Number> entry : seriesContainer) { if(!areaChart.getData().contains(entry)) { areaChart.getData().add(entry); entry.setName("XYChart.Series "+seriesContainer.size()); } } } //Button delete functionality @FXML private void deleteGraph() { } //Button Undo functionality @FXML private void undoGraph(){ } //Button Save functionality @FXML private void saveGraph(){ int max = 0; for(int i =0; i< seriesContainer.size(); i++){ XYChart.Series<Number, Number> test = seriesContainer.get(i); System.out.println("Series "+i+" Employees: "+test.getData().get(i).getYValue().intValue()); System.out.println("Series "+i+" Start: "+test.getData().get(i).getXValue().intValue()); // find maximal y value int x = test.getData().get(i).getYValue().intValue(); if (x > max) { max = x; } System.out.println("Series "+i+" End: "+max); } } @Override public void initialize(URL location, ResourceBundle resources) { areaChart.setTitle("Chronos"); areaChart.getXAxis().setLabel("Heures"); areaChart.getYAxis().setLabel("Employés"); } }

FXML

<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.chart.AreaChart?> <?import javafx.scene.chart.NumberAxis?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.TextField?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.VBox?> <VBox alignment="CENTER" prefHeight="800.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController"> <children> <AreaChart fx:id="areaChart" prefHeight="799.0" prefWidth="800.0" VBox.vgrow="ALWAYS"> <xAxis> <NumberAxis autoRanging="false" minorTickCount="1" minorTickLength="1.0" side="BOTTOM" tickLabelGap="1.0" tickLength="1.0" tickUnit="1.0" upperBound="24.0" fx:id="xAxis" /> </xAxis> <yAxis> <NumberAxis fx:id="yAxis" autoRanging="false" minorTickLength="1.0" side="LEFT" tickLabelGap="1.0" tickUnit="1.0" upperBound="10.0" /> </yAxis> </AreaChart> <HBox alignment="CENTER" prefHeight="193.0" prefWidth="800.0"> <children> <TextField fx:id="txtSt" promptText="Start Value" /> <TextField fx:id="txtEt" promptText="End Value" /> <TextField fx:id="txtNb" promptText="Number of Employees" /> </children> </HBox> <HBox alignment="CENTER" prefHeight="71.0" prefWidth="800.0"> <children> <Button mnemonicParsing="false" onAction="#generateGraph" prefHeight="31.0" prefWidth="137.0" text="Add" /> <Button layoutX="342.0" layoutY="12.0" mnemonicParsing="false" onAction="#deleteGraph" prefHeight="31.0" prefWidth="137.0" text="Delete" /> <Button layoutX="410.0" layoutY="12.0" mnemonicParsing="false" onAction="#undoGraph" prefHeight="31.0" prefWidth="137.0" text="Undo" /> <Button layoutX="479.0" layoutY="10.0" mnemonicParsing="false" onAction="#saveGraph" prefHeight="31.0" prefWidth="137.0" text="Save" /> </children> </HBox> </children> </VBox>

Por favor, alguien me guíe, ¿cómo puedo resolver esto? Por favor, necesito alguna guía sobre cómo almacenar estos datos en H2 dB. Estoy usando JavaFX con Spring Boot.