In this JavaFX example, we will see how to create a Bar Chart using JavaFX.
A bar chart presents grouped data with rectangular bars with lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally.
JavaFX Bar Chart Example
In the example, we use a bar chart to show the number of Olympic gold medals per country in London:package sample;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage stage) {
initUI(stage);
}
private void initUI(Stage stage) {
HBox root = new HBox();
Scene scene = new Scene(root, 480, 330);
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("Gold medals");
BarChart barChart = new BarChart<>(xAxis, yAxis);
barChart.setTitle("Olympic gold medals in London");
XYChart.Series data = new XYChart.Series<String, Number>();
data.getData().add(new XYChart.Data<>("USA", 46));
data.getData().add(new XYChart.Data<>("China", 38));
data.getData().add(new XYChart.Data<>("UK", 29));
data.getData().add(new XYChart.Data<>("Russia", 22));
data.getData().add(new XYChart.Data<>("South Korea", 13));
data.getData().add(new XYChart.Data<>("Germany", 11));
barChart.getData().add(data);
barChart.setLegendVisible(false);
root.getChildren().add(barChart);
stage.setTitle("BarChart");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Related JavaFX Examples
- JavaFX GridPane Example
- JavaFX ColorPicker Example
- JavaFX DatePicker Example
- JavaFX MenuBar Example
- JavaFX Radio Button Example
- JavaFX TabPane Example
- JavaFX Accordion Example
- JavaFX Login Form Validation Example
- JavaFX Form Validation - Registration Form Validation Example
- JavaFX Line Chart Example
- JavaFX Area Chart Example
- JavaFX Scatter Chart Example
- JavaFX Bar Chart Example
- JavaFX Pie Chart Example
- JavaFX Select and Multi-Select Example
- JavaFX Check Box Example
- Java Calculator Project
Comments
Post a Comment
Leave Comment