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

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

the result

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

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

最佳答案

发生了什么事

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

如何解决

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

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

但是为什么呢?

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

在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;

关于java - 透明场景和舞台不适用于 javafx 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36275060/

相关文章:

java - 不支持 SOAP 编码

JavaFX 对话框和警报出现在 RedHat 的主舞台后面

java - `Alert` 有时会出现可笑的小窗口 - 如何解决这个问题?

java - 事件派发线程实际上做了什么?

java - 菜单布局+一些静态和可切换内容

java - 外部类测试需要私有(private)内部类吗?

Java 优先级队列

JavaFX:工作线程需要 JavaFX 应用线程才能继续

java - 有没有办法创建一个与父窗口具有相同属性的子窗口?

javafx - 如何在关闭阶段之前从阶段返回值?