JavaFX: Set gap between graphic node and text in MenuItem Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JavaFX: Set gap between graphic node and text in MenuItem without wasting too much if your time.

The question is published on by Tutorial Guruji team.

What is the way to set a gap between the text and graphic of a MenuItem.

enter image description here

JavaFX Labeled subclasses have a setGraphicTextGap(double value) method that does exactly what I’m looking for, but MenuItem class doesn’t inherit from Labeled.

Sample code:

ImageView newFilterIcon = new ImageView(new Image(newFilterIconUrl));
MenuItem newFilterMenuItem = new MenuItem("New Filter", newFilterIcon);
Menu filterMenu = new Menu("Filter");
filterMenu.getItems().add(newFilterMenuItem);

Answer

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.image.ImageView;
import javafx.stage.Stage;

public class MenuGapApp extends Application {

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

    @Override
    public void start(Stage stage) throws Exception {
        ImageView imageView = new ImageView("https://image.shutterstock.com/image-vector/home-flat-icon-you-can-260nw-451922449.jpg");
        MenuItem menuItem = new MenuItem("New filter", imageView);
        Menu menu = new Menu("Filter", null, menuItem);
        MenuBar menuBar = new MenuBar(menu);
        Scene scene = new Scene(menuBar);
        scene.getStylesheets().add(getClass().getResource("/menu-gap.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }
}

menu-gap.css

.menu-item > .graphic-container {
    -fx-padding: 0em 10em 0em 0em;
}
We are here to answer your question about JavaFX: Set gap between graphic node and text in MenuItem - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji