下面列出了怎么用javafx.scene.control.MenuBar的API类实例代码及写法,或者点击链接到github查看源代码。
private void initializeParts() {
menuBar = new MenuBar();
menu = new Menu("Edit");
preferencesMenuItem = new MenuItem("Preferences");
welcomeLbl = new Label();
brightnessLbl = new Label();
nightModeLbl = new Label();
scalingLbl = new Label();
screenNameLbl = new Label();
resolutionLbl = new Label();
orientationLbl = new Label();
favoritesLbl = new Label();
fontSizeLbl = new Label();
lineSpacingLbl = new Label();
favoriteNumberLbl = new Label();
}
private void initializeParts() {
menuBar = new MenuBar();
menu = new Menu("Edit");
preferencesMenuItem = new MenuItem("Preferences");
welcomeLbl = new Label();
brightnessLbl = new Label();
nightModeLbl = new Label();
scalingLbl = new Label();
screenNameLbl = new Label();
resolutionLbl = new Label();
orientationLbl = new Label();
favoritesLbl = new Label();
fontSizeLbl = new Label();
lineSpacingLbl = new Label();
favoriteNumberLbl = new Label();
}
private void initializeParts() {
menuBar = new MenuBar();
menu = new Menu("Edit");
preferencesMenuItem = new MenuItem("Preferences");
welcomeLbl = new Label();
brightnessLbl = new Label();
nightModeLbl = new Label();
scalingLbl = new Label();
screenNameLbl = new Label();
resolutionLbl = new Label();
orientationLbl = new Label();
favoritesLbl = new Label();
fontSizeLbl = new Label();
lineSpacingLbl = new Label();
favoriteNumberLbl = new Label();
englishBtn = new Button("English");
germanBtn = new Button("German");
}
@Override
public boolean marathon_select(String value) {
MenuBar menuBar = (MenuBar) node;
ObservableList<Menu> menus = menuBar.getMenus();
String[] items = value.split("\\>\\>");
Menu parentMenu = getParentMenu(menus, items[0]);
List<MenuItem> menuItems = new ArrayList<>();
for (int i = 1; i < items.length; i++) {
getChidernMenuItem(parentMenu, items[i], menuItems);
}
parentMenu.fire();
menuItems.stream().forEach((menu) -> {
if (menu instanceof CheckMenuItem) {
CheckMenuItem checkMenuItem = (CheckMenuItem) menu;
checkMenuItem.setSelected(!checkMenuItem.isSelected());
} else if (menu instanceof RadioMenuItem) {
RadioMenuItem radioMenuItem = (RadioMenuItem) menu;
radioMenuItem.setSelected(!isSelected());
}
Platform.runLater(() -> menu.fire());
});
return true;
}
@Override public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new StackPane()));
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
AboutStageBuilder aboutStageBuilder = AboutStageBuilder.start("About MyApp")
.withAppName("MyApp").withCloseOnFocusLoss().withHtml("<i>Some descriptive text</i>")
.withVersionString("Version 1.0b").withCopyright("Copyright \u00A9 " + Calendar
.getInstance().get(Calendar.YEAR));
try {
IcnsParser parser = IcnsParser.forFile(AboutStageBuilder.DEFAULT_APP_ICON);
aboutStageBuilder = aboutStageBuilder.withImage(new Image(parser.getIconStream(IcnsType.ic08)));
} catch (IOException e) {
// Too bad, cannot load dummy image
}
Menu applicationMenu = tk.createDefaultApplicationMenu("MyApp", aboutStageBuilder.build());
MenuBar bar = new MenuBar();
bar.getMenus().add(applicationMenu);
tk.setMenuBar(bar);
}
@Override public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new StackPane()));
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
AboutStageBuilder aboutStageBuilder = AboutStageBuilder.start("About MyApp")
.withAppName("MyApp").withCloseOnFocusLoss().withHtml("<i>Some descriptive text</i>")
.withVersionString("Version 1.0b").withCopyright("Copyright \u00A9 " + Calendar
.getInstance().get(Calendar.YEAR));
try {
IcnsParser parser = IcnsParser.forFile(AboutStageBuilder.DEFAULT_APP_ICON);
aboutStageBuilder = aboutStageBuilder.withImage(new Image(parser.getIconStream(IcnsType.ic08)));
} catch (IOException e) {
// Too bad, cannot load dummy image
}
Menu applicationMenu = tk.createDefaultApplicationMenu("MyApp", aboutStageBuilder.build());
MenuBar bar = new MenuBar();
bar.getMenus().add(applicationMenu);
tk.setMenuBar(bar);
}
@Override
public void start(Stage primaryStage) throws Exception {
MenuToolkit tk = MenuToolkit.toolkit(Locale.getDefault());
tk.setApplicationMenu(tk.createDefaultApplicationMenu("test"));
MenuBar menuBar = new MenuBar();
menuBar.useSystemMenuBarProperty().set(true);
Menu menu = new Menu("java");
MenuItem item = new MenuItem("Test");
Menu help = new Menu("Help");
menu.getItems().add(item);
menuBar.getMenus().addAll(menu, help);
primaryStage.setScene(new Scene(new Pane(menuBar)));
primaryStage.setTitle("Test");
primaryStage.show();
}
private Parent createContent() {
BorderPane root = new BorderPane();
root.setPrefSize(800, 600);
ImageView view1 = new ImageView(new Image("https://placekitten.com/400/550", true));
ImageView view2 = new ImageView();
MenuBar bar = new MenuBar();
Menu menu = new Menu("Filter...");
filters.forEach(filter -> {
MenuItem item = new MenuItem(filter.name);
item.setOnAction(e -> {
view2.setImage(filter.apply(view1.getImage()));
});
menu.getItems().add(item);
});
bar.getMenus().add(menu);
root.setTop(bar);
root.setCenter(new HBox(view1, view2));
return root;
}
@Override
public MenuBar getNode(
PageActionManager actionmanager,
CPageData inputdata,
Window parentwindow,
TabPane[] parenttabpanes,
CollapsibleNode nodetocollapsewhenactiontriggered) {
MenuBar menubar = new MenuBar();
menubar.setStyle("-fx-base: #ffffff; -fx-hover-base: #ddeeff;");
for (int i = 0; i < listofmenus.size(); i++) {
menubar.getMenus().add(listofmenus.get(i).getMenu(actionmanager, inputdata, parentwindow));
}
return menubar;
}
/**
* Add the Windows menu
*/
public static void addWindowsMenu(final Scene scene) {
Parent rootNode = scene.getRoot();
if (rootNode instanceof Pane) {
Pane rootPane = (Pane) rootNode;
MenuBar menuBar = new MenuBar();
menuBar.setUseSystemMenuBar(true);
menuBar.getMenus().add(new WindowsMenu());
rootPane.getChildren().add(menuBar);
}
}
public static Collection<MenuItem> findItemsInMenuWithId(FxRobot robot, String menuToFind) {
MenuBar menuBar = robot.lookup("#mainMenu").query();
MenuItem menu = menuBar.getMenus().stream().flatMap(m-> m.getItems().stream())
.filter(m -> menuToFind.equals(m.getId()))
.findFirst().orElseThrow(RuntimeException::new);
return ((Menu)menu).getItems();
}
private void initializeParts() {
menuBar = new MenuBar();
menu = new Menu("Edit");
preferencesMenuItem = new MenuItem("Preferences");
welcomeLbl = new Label();
brightnessLbl = new Label();
nightModeLbl = new Label();
scalingLbl = new Label();
}
private MenuBar crearteMainMenuBar() {
Menu sessionMenu = new Menu("会话");
loginMenuItem.setOnAction(event -> {
if (loginMenuItem.getUserData() == null || !(boolean) loginMenuItem.getUserData()) {
loginMenuItem.setUserData(true);
Stage loginStage = new Stage();
VBox loginRootVBox = new VBox();
loginStage.setScene(new Scene(loginRootVBox, 240, 120));
loginRootVBox.getChildren().add(loginLayout.getNode());
VBox.setVgrow(loginLayout.getNode(), Priority.ALWAYS);
loginStage.setTitle("登录");
loginStage.initModality(Modality.APPLICATION_MODAL);
loginStage.initOwner(vBox.getScene().getWindow());
loginStage.showAndWait();
loginMenuItem.setUserData(false);
loginRootVBox.getChildren().remove(loginLayout.getNode());
}
});
sessionMenu.getItems().add(loginMenuItem);
MenuItem reloadDataMenuItem = new MenuItem("重新加载数据");
reloadDataMenuItem.setOnAction(event -> {
guiMainService.reloadData();
});
sessionMenu.getItems().add(reloadDataMenuItem);
Menu chartsGroupMenu = new Menu("图表");
MenuItem basicMarketDataChartItem = new MenuItem("新建通用图表");
basicMarketDataChartItem.setOnAction(event -> {
basicMarketDataChartLayout.openBasicMarketDataChartWindow(vBox.getScene().getWindow());
});
chartsGroupMenu.getItems().addAll(basicMarketDataChartItem);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(sessionMenu);
menuBar.getMenus().add(chartsGroupMenu);
return menuBar;
}
private boolean isMenuBar(Node ownerNode) {
Node parent = ownerNode;
while (parent != null) {
if (parent instanceof MenuBar) {
this.menuBar = (MenuBar) parent;
return true;
}
parent = parent.getParent();
}
return false;
}
private static String getName(Node n)
{
Object x = n.getProperties().get(PROP_NAME);
if(x instanceof String)
{
return (String)x;
}
if(n instanceof MenuBar)
{
return null;
}
else if(n instanceof Shape)
{
return null;
}
else if(n instanceof ImageView)
{
return null;
}
String id = n.getId();
if(id != null)
{
return id;
}
return n.getClass().getSimpleName();
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.requestFocus();
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
MenuBar bar = new MenuBar();
MenuItem item1 = new MenuItem("Item1");
MenuItem item2 = new MenuItem("Item2");
MenuItem item3 = new MenuItem("Mute");
item3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Muted");
}
});
MenuItem quit = tk.createQuitMenuItem("mars-sim");
Menu menu2 = new Menu("Menu2");
menu2.getItems().add(item2);
Menu menu1 = new Menu("Menu1");
menu1.getItems().addAll(item1, menu2, quit);
Menu file = new Menu("File");
file.getItems().addAll(item3);
bar.getMenus().addAll(menu1, file);
tk.setMenuBar(primaryStage, bar);
}
/**
* Constructs a blank frame with a desktop pane but no diagram window.
*
* @param pMainStage The main stage used by the UMLEditor
*/
public EditorFrame(Stage pMainStage)
{
aMainStage = pMainStage;
aRecentFiles.deserialize(Preferences.userNodeForPackage(UMLEditor.class).get("recent", "").trim());
MenuBar menuBar = new MenuBar();
setTop(menuBar);
TabPane tabPane = new TabPane();
tabPane.getSelectionModel().selectedItemProperty().addListener((pValue, pOld, pNew) -> setMenuVisibility());
setCenter( tabPane );
List<NewDiagramHandler> newDiagramHandlers = createNewDiagramHandlers();
createFileMenu(menuBar, newDiagramHandlers);
createEditMenu(menuBar);
createViewMenu(menuBar);
createHelpMenu(menuBar);
setMenuVisibility();
aWelcomeTab = new WelcomeTab(newDiagramHandlers);
showWelcomeTabIfNecessary();
setOnKeyPressed(e ->
{
if( !isWelcomeTabShowing() && e.isShiftDown() )
{
getSelectedDiagramTab().shiftKeyPressed();
}
});
setOnKeyTyped(e ->
{
if( !isWelcomeTabShowing())
{
getSelectedDiagramTab().keyTyped(e.getCharacter());
}
});
}
private void setMenuVisibility()
{
((MenuBar)getTop()).getMenus().stream() // All top level menus
.flatMap(menu -> Stream.concat(Stream.of(menu), menu.getItems().stream())) // All menus and immediate sub-menus
.filter( item -> Boolean.TRUE.equals(item.getUserData())) // Retain only diagram-relevant menu items
.forEach( item -> item.setDisable(isWelcomeTabShowing()));
}
private void createFileMenu(MenuBar pMenuBar, List<NewDiagramHandler> pNewDiagramHandlers)
{
MenuFactory factory = new MenuFactory(RESOURCES);
// Special menu items whose creation can't be inlined in the factory call.
Menu newMenu = factory.createMenu("file.new", false);
for( NewDiagramHandler handler : pNewDiagramHandlers )
{
newMenu.getItems().add(factory.createMenuItem(handler.getDiagramType().getName().toLowerCase(), false, handler));
}
aRecentFilesMenu = factory.createMenu("file.recent", false);
buildRecentFilesMenu();
// Standard factory invocation
pMenuBar.getMenus().add(factory.createMenu("file", false,
newMenu,
factory.createMenuItem("file.open", false, event -> openFile()),
aRecentFilesMenu,
factory.createMenuItem("file.close", true, event -> close()),
factory.createMenuItem("file.save", true, event -> save()),
factory.createMenuItem("file.save_as", true, event -> saveAs()),
factory.createMenuItem("file.duplicate", true, event -> duplicate()),
factory.createMenuItem("file.export_image", true, event -> exportImage()),
factory.createMenuItem("file.copy_to_clipboard", true, event -> copyToClipboard()),
new SeparatorMenuItem(),
factory.createMenuItem("file.exit", false, event -> exit())));
}
private void createEditMenu(MenuBar pMenuBar)
{
MenuFactory factory = new MenuFactory(RESOURCES);
pMenuBar.getMenus().add(factory.createMenu("edit", true,
factory.createMenuItem("edit.undo", true, pEvent -> getSelectedDiagramTab().undo()),
factory.createMenuItem("edit.redo", true, pEvent -> getSelectedDiagramTab().redo()),
factory.createMenuItem("edit.selectall", true, pEvent -> getSelectedDiagramTab().selectAll()),
factory.createMenuItem("edit.properties", true, pEvent -> getSelectedDiagramTab().editSelected()),
factory.createMenuItem("edit.cut", true, pEvent -> getSelectedDiagramTab().cut()),
factory.createMenuItem("edit.paste", true, pEvent -> getSelectedDiagramTab().paste()),
factory.createMenuItem("edit.copy", true, pEvent -> getSelectedDiagramTab().copy()),
factory.createMenuItem("edit.delete", true, pEvent -> getSelectedDiagramTab().removeSelected() )));
}
private void createViewMenu(MenuBar pMenuBar)
{
MenuFactory factory = new MenuFactory(RESOURCES);
pMenuBar.getMenus().add(factory.createMenu("view", false,
factory.createCheckMenuItem("view.show_grid", false,
UserPreferences.instance().getBoolean(BooleanPreference.showGrid),
pEvent -> UserPreferences.instance().setBoolean(BooleanPreference.showGrid,
((CheckMenuItem) pEvent.getSource()).isSelected())),
factory.createCheckMenuItem("view.show_hints", false,
UserPreferences.instance().getBoolean(BooleanPreference.showToolHints),
pEvent -> UserPreferences.instance().setBoolean(BooleanPreference.showToolHints,
((CheckMenuItem) pEvent.getSource()).isSelected())),
factory.createCheckMenuItem("view.verbose_tooltips", false,
UserPreferences.instance().getBoolean(BooleanPreference.verboseToolTips),
pEvent -> UserPreferences.instance().setBoolean(BooleanPreference.verboseToolTips,
((CheckMenuItem) pEvent.getSource()).isSelected())),
factory.createCheckMenuItem("view.autoedit_node", false,
UserPreferences.instance().getBoolean(BooleanPreference.autoEditNode),
event -> UserPreferences.instance().setBoolean(BooleanPreference.autoEditNode,
((CheckMenuItem) event.getSource()).isSelected())),
factory.createMenuItem("view.diagram_size", false, event -> new DiagramSizeDialog(aMainStage).show())));
}
public static void register(MenuBar menuBar) {
MENU_BAR = menuBar;
if (instance == null) {
instance = new MenuBarSyncListener();
StageUtils.getStages().addListener(instance);
}
}
public static void setMenuBar(Stage stage, MenuBar menuBar) {
Scene scene = stage.getScene();
if (scene != null) {
ObservableList<Node> children = getChildren(scene.getRoot());
if (children != null) {
setMenuBar(children, menuBar);
}
}
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.requestFocus();
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
MenuBar bar = new MenuBar();
MenuItem item1 = new MenuItem("Item1");
MenuItem item2 = new MenuItem("Item2");
MenuItem item3 = new MenuItem("Item3");
item3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Item3 clicked");
}
});
MenuItem item4 = tk.createQuitMenuItem("my app");
Menu menu2 = new Menu("Menu2");
menu2.getItems().add(item2);
Menu menu1 = new Menu("Menu1");
menu1.getItems().addAll(item1, menu2, item4);
Menu menu3 = new Menu("Menu3");
menu3.getItems().addAll(item3);
bar.getMenus().addAll(menu1, menu3);
tk.setMenuBar(primaryStage, bar);
}
/**
* Invoked by JavaFX for starting the application.
* This method is called on the JavaFX Application Thread.
*
* @param window the primary stage onto which the application scene will be be set.
*/
@Override
public void start(final Stage window) {
this.window = window;
final Vocabulary vocabulary = Vocabulary.getResources((Locale) null);
/*
* Configure the menu bar. For most menu item, the action is to invoke a method
* of the same name in this application class (e.g. open()).
*/
final MenuBar menus = new MenuBar();
final Menu file = new Menu(vocabulary.getString(Vocabulary.Keys.File));
{
final MenuItem open = new MenuItem(vocabulary.getMenuLabel(Vocabulary.Keys.Open));
open.setAccelerator(KeyCombination.keyCombination("Shortcut+O"));
open.setOnAction(e -> open());
final MenuItem exit = new MenuItem(vocabulary.getString(Vocabulary.Keys.Exit));
exit.setOnAction(e -> Platform.exit());
file.getItems().addAll(open, new SeparatorMenuItem(), exit);
}
menus.getMenus().add(file);
/*
* Set the main content and show.
*/
content = new ResourceView();
final BorderPane pane = new BorderPane();
pane.setTop(menus);
pane.setCenter(content.pane);
Scene scene = new Scene(pane);
window.setTitle("Apache Spatial Information System");
window.setScene(scene);
window.setWidth(800);
window.setHeight(650);
window.show();
}
public SpectraIdentificationResultsWindowFX() {
super();
pnMain = new BorderPane();
this.setScene(new Scene(pnMain));
getScene().getStylesheets()
.addAll(MZmineCore.getDesktop().getMainWindow().getScene().getStylesheets());
pnMain.setPrefSize(1000, 600);
pnMain.setMinSize(700, 500);
setMinWidth(700);
setMinHeight(500);
setTitle("Processing...");
pnGrid = new GridPane();
// any number of rows
noMatchesFound = new Label("I'm working on it");
noMatchesFound.setFont(headerFont);
// yellow
noMatchesFound.setTextFill(Color.web("0xFFCC00"));
pnGrid.add(noMatchesFound, 0, 0);
pnGrid.setVgap(5);
// Add the Windows menu
MenuBar menuBar = new MenuBar();
// menuBar.add(new WindowsMenu());
Menu menu = new Menu("Menu");
// set font size of chart
MenuItem btnSetup = new MenuItem("Setup dialog");
btnSetup.setOnAction(e -> {
Platform.runLater(() -> {
if (MZmineCore.getConfiguration()
.getModuleParameters(SpectraIdentificationResultsModule.class)
.showSetupDialog(true) == ExitCode.OK) {
showExportButtonsChanged();
}
});
});
menu.getItems().add(btnSetup);
CheckMenuItem cbCoupleZoomY = new CheckMenuItem("Couple y-zoom");
cbCoupleZoomY.setSelected(true);
cbCoupleZoomY.setOnAction(e -> setCoupleZoomY(cbCoupleZoomY.isSelected()));
menu.getItems().add(cbCoupleZoomY);
menuBar.getMenus().add(menu);
pnMain.setTop(menuBar);
scrollPane = new ScrollPane(pnGrid);
pnMain.setCenter(scrollPane);
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
totalMatches = new ArrayList<>();
matchPanels = new HashMap<>();
setCoupleZoomY(true);
show();
}
public static Collection<MenuItem> findAllMenuItems(FxRobot robot) {
MenuBar menuBar = robot.lookup("#mainMenu").query();
return menuBar.getMenus().stream()
.flatMap(m-> recurseGetAllMenus(robot, m.getItems()).stream())
.collect(Collectors.toList());
}
public IJavaFXElement findMenuBarElement() {
MenuBar menuBar = (MenuBar) getMenuBar().get(0);
IJavaFXElement e = new JavaFXMenuBarElement(menuBar, driver, this);
elements.put(e.createId(), e);
return e;
}
public JavaFXMenuBarElement(MenuBar node, IJavaFXAgent driver, JFXWindow window) {
super(node, driver, window);
}
@Override
protected Pane getMainPane() {
return new StackPane(new MenuBar(new Menu("Menu test")));
}