簡體   English   中英

透明場景和舞台不適用於 javafx 中的按鈕

[英]transparent scene and stage does not work with buttons in javafx

我試圖用按鈕制作一個透明的場景和舞台,但它似乎只適用於 text 。 這是我的簡單代碼

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

結果

但如果我取消注釋按鈕,結果將在這里

它看起來不再透明,但它只是底漆。 那么透明不適用於按鈕嗎? 如果我應該添加一個按鈕呢? 謝謝你 。

這是怎么回事

文本不是控件。 一個僅使用 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM