Wednesday 3 May 2017

JavaFX Pie Chart Example

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class PieChartEx extends Application {
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        HBox root = new HBox();

        Scene scene = new Scene(root, 450, 330);

        ObservableList<PieChart.Data> pieChartData
                = FXCollections.observableArrayList(
                        new PieChart.Data("Apache", 52),
                        new PieChart.Data("Nginx", 31),
                        new PieChart.Data("IIS", 12),
                        new PieChart.Data("LiteSpeed", 2),
                        new PieChart.Data("Google server", 1),
                        new PieChart.Data("Others", 2));

        PieChart pieChart = new PieChart(pieChartData);
        pieChart.setTitle("Web servers market share (2016)");
       
        root.getChildren().add(pieChart);       

        stage.setTitle("PieChart");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


JavaFX Line Chart Example

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class LineChartEx extends Application {
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        HBox root = new HBox();

        Scene scene = new Scene(root, 450, 330);

        NumberAxis xAxis = new NumberAxis();
        xAxis.setLabel("Age");

        NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Salary ($)");

        LineChart lineChart = new LineChart(xAxis, yAxis);
        lineChart.setTitle("Average salary per age");

        XYChart.Series data = new XYChart.Series();
        data.setName("2017");

        data.getData().add(new XYChart.Data(18, 567));
        data.getData().add(new XYChart.Data(20, 612));
        data.getData().add(new XYChart.Data(25, 800));
        data.getData().add(new XYChart.Data(30, 980));
        data.getData().add(new XYChart.Data(40, 1410));
        data.getData().add(new XYChart.Data(50, 2350));

        lineChart.getData().add(data);

        root.getChildren().add(lineChart);

        stage.setTitle("LineChart");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}