Is it possible to, in JavaFX, have a scene, stage, and control that are all transparent?

让人想犯罪 __ 提交于 2020-01-03 04:46:11

问题


I have a custom control which is 3 simple buttons. The control handles operations for the application to which it is tied, but it must reside on an external stage for reasons.

The thing that is annoying about it is that between all buttons is a white background.

I've tried all of the following to eliminate it:

  • Init StageStyle to Transparent
  • Declare Scene with a transparent background : new Scene(Node, X, Y, Color.TRANSPARENT);
  • Declare Scene with a NULL background : new Scene(Node, X, Y, null);
  • Have the control (which extends an HBox) .setStyle("-fx-background-color : rgba(0, 0, 0, 0);");

All of these have failed to eliminate the appearance of the background. I've done this with Windows Forms, but is it possible to do with JavaFX?


回答1:


You need to set the transparency of

  • the stage
  • the scene
  • the root class (or in my case the hbox, i prefer root)

This works for me:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {

            HBox hbox = new HBox();
            hbox.setSpacing(12);

            Button button1 = new Button("Button 1");
            Button button2 = new Button("Button 2");
            Button button3 = new Button("Button 3");

            hbox.getChildren().addAll(button1, button2, button3);

            Scene scene = new Scene(hbox, Color.TRANSPARENT);

//          scene.getStylesheets().add( getClass().getResource("application.css").toExternalForm());
            scene.getRoot().setStyle("-fx-background-color: transparent");

            primaryStage.initStyle(StageStyle.TRANSPARENT);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

That's the direct solution. Of course instead of setting the style directly it's better practice to use a stylesheet application.css:

.root {
    -fx-background-color: transparent;
}

Here's a screenshot with the application being over the code:



来源:https://stackoverflow.com/questions/27468195/is-it-possible-to-in-javafx-have-a-scene-stage-and-control-that-are-all-tran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!