透明场景和舞台不适用于 javafx 中的按钮

ahm*_*raf 4 java javafx

我正在尝试使用按钮制作透明场景和舞台,但它似乎仅适用于文本。这是我的简单代码

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class TransparentStage extends Application {

@Override
public void start(Stage stage) {
    stage.initStyle(StageStyle.TRANSPARENT);
    Text text = new Text("Transparent!");
    text.setFont(new Font(40));
    //Button button = new Button("btn");
    VBox box = new VBox();
    box.getChildren().add(text);
    //box.getChildren().add(button);
    final Scene scene = new Scene(box,300, 300);
    scene.setFill(Color.TRANSPARENT);
    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)

结果

但如果我取消注释按钮,结果将在这里

它看起来不再透明,但只是有底漆。那么透明不适用于按钮吗?如果我应该添加一个按钮呢?谢谢 。

jew*_*sea 5

这是怎么回事

文本不是控件。一个简单的 JavaFX 程序,仅使用 Text,不加载任何控件。要使用控件,JavaFX 需要加载默认的 CSS 样式表(在 Java 8 中,这称为modena.css)。默认 CSS 样式表将为布局窗格(例如您在示例中使用的 VBox)设置背景颜色。

如何修复它

使用 CSS 修复

要防止布局窗格出现背景色,您需要将其背景色设置为 null:

box.setStyle("-fx-background-color: null;");
Run Code Online (Sandbox Code Playgroud)

或者,不使用 CSS 进行修复

box.setBackground(null);
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请参阅Region.setBackground()

背景有可能为空,即既没有填充也没有图像,并且在语义上等同于 null。

如果您使用代码中的方法设置背景setBackground(),这将优先于 CSS 设置(因此 CSS 设置将不适用)。

但为什么?

现在,我知道这很奇怪。。。但这就是事实。如果不使用控件,则布局窗格没有背景颜色,因为 CSS 未加载并应用于场景图(可能是出于性能原因)。如果您使用控件,则会加载 CSS 并且布局窗格具有背景颜色。

在 modena.css 中,该部分的定义.root是:

/* A very light grey used for the background of windows.  See also
 * -fx-text-background-color, which should be used as the -fx-text-fill
 * value for text painted on top of backgrounds colored with -fx-background.
 */
-fx-background: derive(-fx-base,26.4%);  

/* A light grey that is the base color for objects.  Instead of using
 * -fx-base directly, the sections in this file will typically use -fx-color.
 */
-fx-base: #ececec;

/***************************************************************************
 *                                                                         *
 * Set the default background color for the scene                          *
 *                                                                         *
 **************************************************************************/

-fx-background-color: -fx-background;
Run Code Online (Sandbox Code Playgroud)