如何在 JavaFX 图表中设置背景图片?
javafx.scene.chart 包提供了创建各种图表(例如:线形图、区域图、柱状图、饼图、气泡图、散点图等)的类。
您可以通过实例化相应的类来创建所需的图表。
设置背景图片和颜色
JavaFX CSS 的 -fx-background-image 类用于将图片设置为图表的背景。
JavaFX CSS 的 -fx-background-color(区域 chart-plot-background)类用于设置背景颜色。
JavaFX 的 Scene 类有一个可观察列表来保存所有所需的样式表。您可以使用 getStylesheets() 方法获取此列表。
要将图片设置为图表的背景:
在项目的当前包中创建一个 CSS 文件(例如 LineChart.css)。
使用 -fx-background-image CSS 类设置背景图片:
.chart-plot-background {
-fx-background-image: url("cat.jpg");
}使用 -fx-background-color CSS 类将绘图颜色设置为透明:
.chart-plot-background {
-fx-background-color: transparent;
}在程序中,使用 getStylesheets() 方法获取样式表的可观察列表。
使用 add() 方法将创建的 CSS 文件添加到列表中。
示例
LineChart.CSS:
.chart {
-fx-padding: 10px;
-fx-background-image: url("cat.jpg");
}
.chart-plot-background {
-fx-background-color: transparent;
}
.chart-vertical-grid-lines {
-fx-stroke: #dedddc; -fx-stroke-width: 2;
}
.chart-horizontal-grid-lines {
-fx-stroke: #dedddc; -fx-stroke-width: 2;
}Example.java:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BubbleChart;
import javafx.stage.Stage;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class Example extends Application {
public void start(Stage stage) {
//Defining the axes
NumberAxis xAxis = new NumberAxis(0, 100, 10);
xAxis.setLabel("Age");
NumberAxis yAxis = new NumberAxis(20, 100, 10);
yAxis.setLabel("Weight");
//Creating the Bubble chart
BubbleChart bubbleChart = new BubbleChart(xAxis, yAxis);
//Prepare XYChart.Series objects by setting data
XYChart.Series series = new XYChart.Series();
series.setName("work");
series.getData().add(new XYChart.Data(10,30,4));
series.getData().add(new XYChart.Data(25,40,5));
series.getData().add(new XYChart.Data(40,50,9));
series.getData().add(new XYChart.Data(55,60,7));
series.getData().add(new XYChart.Data(70,70,9));
series.getData().add(new XYChart.Data(85,80,6));
//Setting the data to bar chart
bubbleChart.getData().add(series);
//Creating a Group object
StackPane root = new StackPane(bubbleChart);
//Setting a scene
Scene scene = new Scene(root, 595, 300);
stage.setTitle("Bubble Chart");
scene.getStylesheets().add("styles/LineChart.css");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP