A Chart.js 4+ Wrapper for Vaadin
For more and detailed usage examples please have a look at the demo.
// Assumes that this code is in some kind of Vaadin component or view
ChartContainer chart = new ChartContainer();
this.add(chart);
chart.showChart(
"{\"data\":{\"labels\":[\"A\",\"B\"],\"datasets\":[{\"data\":[1,2],\"label\":\"X\"}]},\"type\":\"bar\"}");
// Or utilizing chartjs-java-model
chart.showChart(new BarChart(new BarData()
.addLabels("A", "B")
.addDataset(new BarDataset()
.setLabel("X")
.addData(1)
.addData(2)))
.toJson());
- Use a Java model of Java model of Chart.js's configuration, like XDEV's chartjs-java-model.
Otherwise you have to write the JSON yourself. - Optionally derive classes for your charts (from e.g.
ChartContainer
) that also handle the data-to-JSON conversion logic.
Therefore you can encapsulate the components properly, for example like this:FetchFromBackendService.class → Model for chart → ChartContainer.class → Build JSON and show chart
Here is a example how the code could look (click to expand)
- Define a custom chart or use the
showChart
-method directly.
Example:public class ExampleChartContainer extends ChartContainer { public void show(Data data) { BarData data = ...; // Build the bar chart data from the handed over data this.showChart(new BarChart(data) .setOptions(new BarOptions() .setResponsive(true) .setMaintainAspectRatio(false) .setPlugins(new Plugins() .setTitle(new Title() .setText("Age") .setDisplay(true)))) .toJson()); } }
- Add the chart to your view/component:
public class ExampleView extends VerticalLayout { private final ExampleChartContainer chart = new ExampleChartContainer(); public ExampleView() { this.add(this.chart); // ... } private void loadDataAndShowChart() { this.chart.showLoading(); UI ui = UI.getCurrent(); CompletableFuture.runAsync(() -> { try { var data = ...; // Load some data from the backend // You may also convert the data here and call showChart ui.access(() -> this.chart.show(data)); } catch (Exception ex) { // Display the error message when loading fails ui.access(() -> this.chart.showFailed(ex.getMessage())); } }); } }
Installation guide for the latest release
- You may have to include
software/xdev
insidevaadin.allowed-packages
- Checkout the repo
- Run
mvn install && mvn -f vaadin-chartjs-wrapper-demo spring-boot:run
- Open http://localhost:8080
If you need support as soon as possible and you can't wait for any pull request, feel free to use our support.
See the contributing guide for detailed instructions on how to get started with our project.
View the license of the current project or the summary including all dependencies
Disclaimer: This is not an official Chart.js product and not associated