如何在 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); } }
輸出
廣告