以下CSS将使
BarChart
中的所有元素除了柱形本身之外都不可见/透明。
.bar-chart {
-fx-alternative-row-visible: false;
-fx-alternative-column-visible: false;
-fx-horizontal-grid-lines-visible: false;
-fx-vertical-grid-lines-visible:false;
-fx-horizontal-zero-line-visible: false;
-fx-vertical-zero-line-visible: false;
-fx-legend-visible: false;
}
.chart-plot-background {
-fx-background-color: transparent;
}
.axis {
-fx-border-color: transparent;
-fx-tick-mark-visible: false;
-fx-minor-tick-visible: false;
-fx-tick-labels-visible: false;
}
以下是一个使用上述方法的示例(假设文件名为
Main.css
):
import java.util.Random;
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.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
var scene = new Scene(new StackPane(createBarChart()), Color.TRANSPARENT);
scene.getStylesheets().add("Main.css");
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setScene(scene);
primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ESCAPE) {
primaryStage.close();
}
});
var bounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX(bounds.getMinX());
primaryStage.setY(bounds.getMinY());
primaryStage.setWidth(bounds.getWidth());
primaryStage.setHeight(bounds.getHeight());
primaryStage.show();
}
private BarChart<?, ?> createBarChart() {
var chart = new BarChart<>(new CategoryAxis(), new NumberAxis(0, 20, 1));
var random = new Random();
var series = new Series<String, Number>();
for (int i = 0; i < 20; i++) {
var category = Integer.toString(i);
series.getData().add(new Data<>(category, random.nextInt(15)));
((CategoryAxis) chart.getXAxis()).getCategories().add(category);
}
chart.getData().add(series);
return chart;
}
}
这是结果的图片:
![示例截图](https://istack.dev59.com/mWV87.webp)
我稍微修改了CSS文件,使得
Scene
的根部透明,并让条形图呈现线性渐变的外观。我所做的只是……
.root,
.chart-plot-background {
-fx-background-color: transparent;
}
并添加以下内容:
.chart-bar {
-fx-background-color: linear-gradient(to bottom, transparent 0%, gray 45%);
}