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

时间:2016-03-29 03:49:12

标签: 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

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

1 个答案:

答案 0 :(得分:2)

发生了什么

文字不是控件。一个只使用Text的简单JavaFX程序不会加载任何控件。要使用控件,JavaFX需要加载默认的CSS样式表(在Java 8中,这称为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;
相关问题