/ Published in: Java
Cumbersome but effective code to creating a menu bar
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCombination; import javafx.scene.input.MouseButton; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Stop; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class MenuExample extends Application { launch(args); } private Stage stage = null; itemNew.setAccelerator(KeyCombination.keyCombination("Ctrl+N")); // create open menu item // create exit menu item itemExit.setAccelerator(KeyCombination.keyCombination("Ctrl+X")); itemExit.setOnAction(event -> { // stop the application stage.hide(); }); // add menu items to the menu fileMenu.getItems().addAll( itemNew, itemOpen, itemExit ); return fileMenu; } // add menu items to the menu editMenu.getItems().addAll( itemCopy, itemCut, createPasteMenu() ); return editMenu; } itemPasteAsFormatting.setOnAction(event -> System.out.println("Paste as Formatting menu item clicked.")); // add menu items to the menu pasteMenu.getItems().addAll( itemPasteAsText, itemPasteAsContent, itemPasteAsFormatting ); return pasteMenu; } menuBar.getMenus().addAll( createFileMenu(), createEditMenu() ); return menuBar; } public ContextMenu createContextMenu() { ContextMenu contextMenu = new ContextMenu( createFileMenu(), createEditMenu() ); return contextMenu; } public Scene createScene() { BorderPane bp = new BorderPane(); VBox center = new VBox(); center.setSpacing(10); center.getChildren().addAll( createMenuButton(), createSplitMenuButton(), rect ); // make the context menu appear when right-click on the center VBox ContextMenu contextMenu = createContextMenu(); rect.setOnMousePressed(event -> { if (event.getButton() == MouseButton.SECONDARY) { contextMenu.show(stage, event.getScreenX(), event.getScreenY()); } }); // set the menu bar to the top section, rest in center bp.setTop(createMenuBar()); bp.setCenter(center); return new Scene(bp, 500, 400); } @Override stage = primaryStage; primaryStage.setTitle("Example 1"); primaryStage.setScene(createScene()); primaryStage.show(); } }
URL: manualmenujava