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

透明场景和舞台不适用于javafx中的按钮,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 java

我试图用按钮制作一个透明的场景和舞台,但它似乎只适用于文本。 这是我的简单代码

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

但是如果我取消对按钮的注释,结果将是

它看起来不再透明了,但它只是涂了一层底漆。 那么“透明”不适用于按钮? 如果我要加一个按钮呢? 谢谢。

发生了什么事

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

如何修复它

要防止布局窗格使用背景色,需要将其背景色设置为null:

box.setStyle("-fx-background-color: null;");
但是为什么呢

现在,我知道这很奇怪。但事实就是这样。如果不使用控件,则布局窗格没有背景色,因为未加载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;