JavaFX - what is this weird container that contains a context menu

I started styling one of my apps and I noticed something strange. This is an example that reflects this behavior. As you can see, there is a menu with three items. I created a context menu (orange), but it looks like the context menu is in another wider container that holds it. What is this container and how can you style it to get a natural menu.

enter image description here

Here's the code too:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;


public class TestMenu extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        BorderPane borderPane = new BorderPane();
        MenuBar menuBar = new MenuBar();
        Menu menu = new Menu("File");
        MenuItem menuItemSettings = new MenuItem("Settings");
        MenuItem menuItemOpen = new MenuItem("Open");
        MenuItem menuItemFile = new MenuItem("Exit");

        TextField textField = new TextField();
        textField.setPrefColumnCount(25);

        menuBar.getMenus().addAll(menu);
        menu.getItems().addAll(menuItemSettings, menuItemOpen, menuItemFile);
        borderPane.setTop(menuBar);
        borderPane.setCenter(textField);
        Scene scene = new Scene(borderPane, 320, 200);
        scene.getStylesheets().addAll("/testcss/style.css");
        stage.setScene(scene);
        stage.show();
    }

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

      

And the stylesheet:

.root {
    -fx-background-color: #222;
}

.text {
    -fx-fill: white;
}

.menu-bar {
    -fx-background-color: #007fa8;
}

.menu-item {
     -fx-background-color: #222;
}

.menu-item:hover {
    -fx-background-color: #3399B9;
}

.menu-item:pressed {
    -fx-background-color: #004C65;
}

.context-menu {
    -fx-background-color: orange;
}

      

Thanks in advance.

+3


source to share


1 answer


As you can read here :

PopupWindow has its own scene. By default, the root directory gets the style class .root

and

the root scene PopupWindow is styled differently using the CSS.root.popup rule {/ * declarations * /}



So basically what happens is that you apply the same dark background of your scene to the popup menu that shows the menu.

Whether you want a different background or not, you just need to add the following CSS rule to your css file:

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

      

+3


source







All Articles