Gregor
Gregor

Reputation: 449

Menu button style while menu open JavaFX

I was wondering if I can set a certain style (e.g. background color to black) for a menu button while the menu of this menu button is currently open. That is, if the menu is not open, then it should not have a black background color. Can I do this in the CSS file or is it even possible?

I know the menu buttons has a method showing which indicates me, whether the menu is open, but I don't know to apply this, so that the button color changes while the menu is open.

This is the menu button: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/MenuButton.html

I'm using JavaFX and for the styling I'm using CSS.

Upvotes: 0

Views: 425

Answers (1)

James_D
James_D

Reputation: 209694

The documentation indicates that MenuButton has a showing pseudoclass that is set when the context menu is showing, so you can do

.menu-button:showing {
  -fx-base: black ;
}

Here's a quick test harness:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class App extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        MenuButton button = new MenuButton("Test");
        button.getItems().addAll(
                new MenuItem("Item 1"),
                new MenuItem("Item 2")
        );
        BorderPane root = new BorderPane();
        root.setTop(button);
        Scene scene = new Scene(root, 200, 200);
        scene.getStylesheets().add(getClass().getResource("/style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

from which I got the following:

enter image description here

and

enter image description here

Upvotes: 2

Related Questions