How to create a SplitMenuButton in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.

A button controls in user interface applications, in general, on clicking the button it performs the respective action.

A SplitMenuButton provides the functionality of both buttons and a Menu. It is divided into two areas − action area and, menu area. On clicking either of these areas it shows the respective functionality.

You can create a split menu button by instantiating the javafx.scene.control.SplitMenuButton class.

Example

The following Example demonstrates the creation of a SplitMenuButton.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitMenuButton;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class SplitMenuButtonExample extends Application {
   public void start(Stage stage) {
      //Creating an ImageView
      ImageView img = new ImageView("UIControls/globe.png");
      img.setFitWidth(20);
      img.setFitHeight(20);
      //Creating a label
      Label label = new Label("Select A Language");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a menu
      SplitMenuButton menu = new SplitMenuButton();
      //Setting text to the SplitMenuButton
      menu.setText("Language");
      //Setting an image to the button
      menu.setGraphic(img);
      //Creating menu Items
      menu.setMnemonicParsing(true);
      MenuItem item1 = new MenuItem("Telugu");
      MenuItem item2 = new MenuItem("Hindi");
      MenuItem item3 = new MenuItem("English");
      MenuItem item4 = new MenuItem("Tamil");
      MenuItem item5 = new MenuItem("Malayalam");
      //Adding all the menu items to the menu
      menu.getItems().addAll(item1, item2, item3, item4, item5);
      //Adding the choice box to the scene
      HBox layout = new HBox(25);
      layout.getChildren().addAll(label, menu);
      layout.setPadding(new Insets(15, 50, 50, 130));
      layout.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(layout, 595, 200);
      stage.setTitle("Split Menu Button");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 20-May-2020 11:19:43
Advertisements