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

问题描述 投票:0回答:1

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

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);
}
}

the result

但是如果我取消注释该按钮,结果将是 here

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

java javafx
1个回答
5
投票

发生什么事了

文本不是控件。一个简单的 JavaFX 程序,仅使用 Text,不加载任何控件。要使用控件,JavaFX 需要加载默认的 CSS 样式表(在 Java 8 中,这称为

modena.css
)。默认 CSS 样式表将为布局窗格设置背景颜色,例如您在示例中使用的 VBox。

如何解决

使用CSS修复

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

box.setStyle("-fx-background-color: null;");

或者,无需 CSS 即可修复

box.setBackground(null);

欲了解更多信息,请参阅

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;
© www.soinside.com 2019 - 2024. All rights reserved.