Прозрачная сцена и сцена JavaFX

Я новичок в JavaFX, я пытаюсь создать прозрачную сцену и поставить проблему, когда я добавляю узлы, такие как изображения и метки, сцена больше не прозрачна, это мой код

package application;




import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;



public class Main extends Application { 

    private double xOffset = 0;
    private double yOffset = 0;
    public void start(Stage primaryStage) throws Exception {
    try{ 

        Parent root ;
        root = FXMLLoader.load(getClass().getResource("/View/Authentification.fxml"));

        primaryStage.initStyle(StageStyle.TRANSPARENT);
        Scene scene = new Scene(root);
        scene.setFill(null);

         root.setOnMousePressed(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    xOffset = event.getSceneX();
                    yOffset = event.getSceneY();
                }
            });
            root.setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    primaryStage.setX(event.getScreenX() - xOffset);
                    primaryStage.setY(event.getScreenY() - yOffset);
                }
            });


        primaryStage.setScene(scene);

    primaryStage.show();}
     catch(Exception e) {
            e.printStackTrace();
        }  
    }
    public static void main(String[] args) {
        launch(args);
    }
}

и это мой xml-код:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">

      <AnchorPane layoutY="94.0" prefHeight="417.0" prefWidth="363.0" style="-fx-background-color: #3D4966;"/>
      <AnchorPane layoutX="-1.0" prefHeight="82.0" prefWidth="363.0" style="-fx-background-color: #3D4966;">
      <children>
      <Label layoutX="280.0" layoutY="70.0" text="Fermer" textFill="#eee5e5">
         <font>
            <Font name="System Bold" size="12.0" />
         </font>
      </Label>
      <ImageView layoutX="288.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../images/Shutdown.png" />
         </image>
      </ImageView>
      <Label layoutX="146.0" layoutY="61.0" prefHeight="17.0" prefWidth="92.0" text="crée un compte" textFill="#eee5e5">
         <font>
            <Font name="System Bold" size="12.0" />
         </font>
      </Label>
      <ImageView layoutX="167.0" layoutY="21.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../images/Add_User.png" />
         </image>
      </ImageView>
      <ImageView layoutX="50.0" layoutY="21.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../images/User.png" />
         </image>
      </ImageView>
      <Label layoutX="50.0" layoutY="62.0" text="Ce connecter" textFill="#eee5e5">
         <font>
            <Font name="System Bold" size="12.0" />
         </font>
      </Label>
   </children>
   </AnchorPane>


</AnchorPane>

я пробовал много других кодов, но ничего не работает, это несколько скриншотов с узлами

без узлов


person Alia Al-Nighaoui    schedule 23.01.2018    source источник
comment
Каждый элемент управления в JavaFx может быть прозрачным. Я не читал ваш код, но полагаю, вы не применили атрибут «прозрачный» ко всем элементам управления (узлам).   -  person zlakad    schedule 23.01.2018


Ответы (1)


Если вы создаете один или несколько элементов управления (в частности, любой экземпляр Control или подкласса), к сцене применяется таблица стилей по умолчанию. Это устанавливает цвет фона корня сцены на непрозрачный «очень светло-серый» (в основном на 26,4% светлее, чем #ececec).

(В частности, таблица стилей по умолчанию содержит следующее:

.root {
    /***************************************************************************
     *                                                                         *
     * The main color palette from which the rest of the colors are derived.   *
     *                                                                         *
     **************************************************************************/

    /* 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;

    /* 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%);

    /* ... */

    -fx-background-color: -fx-background;

}

Источник текущей версии таблицы стилей по умолчанию (на момент написания) можно найти по адресу http://hg.openjdk.java.net/openjfx/9/rt/file/c734b008e3e8/modules/.javafx.controls/src/main/resources/com/sun/javafx/scene/control/skin/modena/modena.css).

Поэтому вам также нужно сделать прозрачным корень сцены.

Вы можете сделать это, используя встроенный CSS, либо в FXML:

<AnchorPane style="-fx-background-color: transparent ;" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">

или в Java:

    Parent root ;
    root = FXMLLoader.load(getClass().getResource("/View/Authentification.fxml"));
    root.setStyle("-fx-background-color: transparent ;");

или вы можете сделать это во внешней таблице стилей:

.root {
    -fx-background-color: transparent ;
}
person James_D    schedule 23.01.2018