Is it possible to, in JavaFX, have a scene, stage,

2019-06-10 01:14发布

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条回答
祖国的老花朵
2楼-- · 2019-06-10 01:30

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:

enter image description here

查看更多
登录 后发表回答