下面列出了怎么用javafx.scene.control.MenuItem的API类实例代码及写法,或者点击链接到github查看源代码。
private void initRecentFiles() {
Config.getInstance().readConfig();
ArrayList<String> paths = Config.getInstance().getFilePaths();
for (String path : paths) {
MenuItem item = new MenuItem(path);
item.setOnAction(e -> {
File file = new File(path);
if(file.exists()){
readMapWithAlert(new File(path));
} else {
AlertDialog.showAlertDialog("地图文件不存在");
mRecentMenu.getItems().remove(this);
removeRecentFile(file);
}
});
mRecentMenu.getItems().add(item);
}
}
@Test
public void duplicateMenuPath() {
List<String> path = new ArrayList<>();
Platform.runLater(() -> {
Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Shuffle");
MenuItem clear = new MenuItem("Clear");
MenuItem clear1 = new MenuItem("Clear");
MenuItem clear2 = new MenuItem("Clear");
MenuItem exit = new MenuItem("Exit");
menuFile.getItems().addAll(add, clear, clear1, clear2, new SeparatorMenuItem(), exit);
RFXMenuItem rfxMenuItem = new RFXMenuItem(null, null);
path.add(rfxMenuItem.getSelectedMenuPath(clear2));
});
new Wait("Waiting for menu selection path") {
@Override
public boolean until() {
return path.size() > 0;
}
};
AssertJUnit.assertEquals("File>>Clear(2)", path.get(0));
}
/**
* Constructor.
*
* @param text the label to use for the text. Styles will be copied from
* this label.
* @param wrapText specifies whether text wrapping is allowed in this label.
* @param style the CSS style of the label. This can be null.
* @param tipsPane the tooltip for the label. This can be null.
* @param contextMenuItems a list of menu items to add to the context menu
* of the label. This can be null.
*/
public SelectableLabel(final String text, boolean wrapText, String style, final TooltipPane tipsPane, final List<MenuItem> contextMenuItems) {
getStyleClass().add("selectable-label");
setText(text == null ? "" : text);
setWrapText(wrapText);
setEditable(false);
setPadding(Insets.EMPTY);
setCache(true);
setCacheHint(CacheHint.SPEED);
setMinHeight(USE_PREF_SIZE);
if (style != null) {
setStyle(style);
}
if (tipsPane != null) {
TooltipUtilities.activateTextInputControl(this, tipsPane);
}
this.contextMenuItems = contextMenuItems;
}
/** @param entry {@link MenuEntry}
* @return {@link MenuItem}
*/
private MenuItem createMenuItem(final MenuEntry entry)
{
final MenuItem item = new MenuItem(entry.getName());
final Image icon = entry.getIcon();
if (icon != null)
item.setGraphic(new ImageView(icon));
item.setOnAction(event ->
{
try
{
entry.call();
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error invoking menu " + entry.getName(), ex);
}
});
return item;
}
private void createURLLink(String pattern, String id, String icon) {
MenuItem tmsMenuItem = new MenuItem(id, FXUIUtils.getIcon(icon));
if (pattern != null && pattern.length() > 0) {
String url = String.format(pattern, id);
tmsMenuItem.setOnAction((event) -> {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
});
} else {
tmsMenuItem.setDisable(true);
}
infoButton.getItems().add(tmsMenuItem);
}
/**
* Fill the items actions for this node.
*
* @param nodeTree the node tree
* @param items the items
*/
@FxThread
public void fillContextMenu(@NotNull final NodeTree<?> nodeTree, @NotNull final ObservableList<MenuItem> items) {
if (canEditName()) {
items.add(new RenameNodeAction(nodeTree, this));
}
if (canCopy()) {
items.add(new CopyNodeAction(nodeTree, this));
}
final Clipboard clipboard = Clipboard.getSystemClipboard();
final Object content = clipboard.getContent(DATA_FORMAT);
if (!(content instanceof Long)) {
return;
}
final Long objectId = (Long) content;
final TreeItem<?> treeItem = UiUtils.findItem(nodeTree.getTreeView(), objectId);
final TreeNode<?> treeNode = treeItem == null ? null : (TreeNode<?>) treeItem.getValue();
if (treeNode != null && canAccept(treeNode, true)) {
items.add(new PasteNodeAction(nodeTree, this, treeNode));
}
}
@FXML
private void showRecentMenu(MouseEvent event) {
hideMenu(event);
popMenu = new ContextMenu();
popMenu.setAutoHide(true);
popMenu.getItems().addAll(getRecentMenu());
popMenu.getItems().add(new SeparatorMenuItem());
MenuItem closeMenu = new MenuItem(message("MenuClose"));
closeMenu.setStyle("-fx-text-fill: #2e598a;");
closeMenu.setOnAction((ActionEvent cevent) -> {
popMenu.hide();
popMenu = null;
});
popMenu.getItems().add(closeMenu);
showMenu(recentBox, event);
view.setImage(new Image("img/RecentAccess.png"));
text.setText(message("RecentAccessImageTips"));
locateImage(recentBox, true);
}
private Button buildMenuItem(MenuItem item) {
Button button = new Button();
button.textProperty().bind(item.textProperty());
button.graphicProperty().bind(item.graphicProperty());
button.disableProperty().bind(item.disableProperty());
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.getStyleClass().addAll(item.getStyleClass());
button.setOnAction(item.getOnAction());
// Only in cases ALWAYS and SOMETIMES: hide previously hovered button
if (!Priority.NEVER.equals(getSkinnable().getMenuHoverBehavior())) {
button.addEventHandler(MouseEvent.MOUSE_ENTERED, e -> { // Triggers on hovering over Button
if (!isTouchUsed) {
if (hoveredBtn != null) {
hoveredBtn.hide(); // Hides the previously hovered Button if not null
}
hoveredBtn = null; // Sets it to null
}
});
}
return button;
}
private String getTagForMenu(MenuItem source) {
LinkedList<MenuItem> menuItems = new LinkedList<>();
while (source != null) {
menuItems.addFirst(source);
source = source.getParentMenu();
}
if (menuItems.getFirst() instanceof Menu) {
if (menuItems.size() >= 2) {
ownerNode = menuItems.get(1).getParentPopup().getOwnerNode();
return isMenuBar(ownerNode) ? "#menu" : "#contextmenu";
}
} else {
ownerNode = menuItems.getFirst().getParentPopup().getOwnerNode();
return "#contextmenu";
}
return null;
}
@Override
public void start(final Stage stage)
{
final MenuButton button1 = new MenuButton("Plain Button", null, new MenuItem("Item 1"), new MenuItem("Item 2"));
button1.getStyleClass().add("action_button");
final MenuItem item = new MenuItem("Action Button Item");
item.getStyleClass().add("action_button_item");
final MenuButton button2 = new MenuButton("Dark Button", null, item, new MenuItem("Plain Item"));
button2.setStyle(JFXUtil.shadedStyle(new WidgetColor(100, 0, 0)));
button2.setTextFill(Color.YELLOW);
button2.getStyleClass().add("action_button");
final HBox box = new HBox(button1, button2);
final Scene scene = new Scene(box, 800, 700);
// XXX Enable scenic view to debug styles
// ScenicView.show(scene);
JFXRepresentation.setSceneStyle(scene);
stage.setScene(scene);
stage.setTitle("MenuButtons");
stage.show();
}
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");
}
public LyricsTextArea() {
textArea = new InlineCssTextArea();
ContextMenu contextMenu = new ContextMenu();
Clipboard systemClipboard = Clipboard.getSystemClipboard();
MenuItem paste = new MenuItem(LabelGrabber.INSTANCE.getLabel("paste.label"));
contextMenu.setOnShown(e -> {
paste.setDisable(!systemClipboard.hasContent(DataFormat.PLAIN_TEXT));
});
paste.setOnAction(e -> {
String clipboardText = systemClipboard.getString();
textArea.insertText(textArea.getCaretPosition(), clipboardText);
});
contextMenu.getItems().add(paste);
textArea.setContextMenu(contextMenu);
textArea.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
Platform.runLater(this::refreshStyle);
});
textArea.setStyle("-fx-font-family: monospace; -fx-font-size: 10pt;");
textArea.setUndoManager(UndoManagerFactory.zeroHistorySingleChangeUM(textArea.richChanges()));
getChildren().add(new VirtualizedScrollPane<>(textArea));
textArea.getStyleClass().add("text-area");
}
public void openOpenNewTabMenu() {
if (root.getSelectionModel().getSelectedItem() != null) {
Tab selectedFile = root.getSelectionModel().getSelectedItem();
ContextMenu contextMenu = new ContextMenu();
for (EditorView ev : editorController.getRegisteredEditors()) {
MenuItem item = new MenuItem(ev.getDisplayName());
item.setOnAction(event -> {
openNewEditor(selectedFile, ev);
});
contextMenu.getItems().add(item);
}
contextMenu.setOnHidden(event -> {
isMenuOpen = false;
});
Point p = MouseInfo.getPointerInfo().getLocation();
contextMenu.show(root.getScene().getWindow(), p.x, p.y);
}
}
@Override
public void load() {
super.load();
Platform.runLater(new Runnable() { // this will run initFX as JavaFX-Thread
@Override
public void run() {
webView.setContextMenuEnabled(false);
contextMenu = new ContextMenu();
open = new MenuItem("Open in browser");
addActionListener();
addContextMenuListener();
contextMenu.getItems().addAll(open);
}
});
}
public Node getNode()
{
final TextField channels = new TextField();
channels.setEditable(false);
channels.setTooltip(new Tooltip("Channel selection"));
channelSelection.addListener((obs, oldv, newv) -> channels.setText(String.join(", ", IntStream.of(newv).boxed().map(Object::toString).toArray(String[]::new))));
MenuItem all = new MenuItem("_All");
all.setOnAction(e -> channelSelection.set(range()));
MenuItem revert = new MenuItem("_Revert");
revert.setOnAction(e -> channelSelection.set(reverted(channelSelection.get())));
MenuItem everyNth = new MenuItem("Every _Nth");
everyNth.setOnAction(e -> everyNth(numChannels.get()).ifPresent(channelSelection::set));
final MenuButton selectionButton = new MenuButton("_Select", null, all, revert, everyNth);
HBox.setHgrow(channels, Priority.ALWAYS);
return new VBox(
new Label("Channel Settings"),
new HBox(channels, selectionButton));
}
private void updateUI(final DisplayNavigation navigation)
{
final List<DisplayInfo> displays = getDisplays();
final int N = displays.size();
if (N<=0)
{
image.setImage(disabled);
getItems().clear();
}
else
{
image.setImage(icon);
final List<MenuItem> items = new ArrayList<>(N);
for (int i=0; i<N; ++i)
items.add(createNavigationItem(displays.get(N-i-1), i+1));
getItems().setAll(items);
}
}
private void onContextMenuEvent(ContextMenuEvent event) {
ObjectTag selected = selectedObjectProperty.get();
if (selected == null) {
return;
}
contextMenu = new ContextMenu();
for (int i = 0; i < 10 && i < Settings.recentNamesProperty.size(); i++) {
NameColor nameColor = Settings.recentNamesProperty.get(i);
String name = nameColor.getName();
if (name.isEmpty() || name.isBlank()) {
continue;
}
MenuItem mi = new MenuItem(name);
mi.setOnAction(value -> {
selected.nameProperty().set(name);
Settings.recentNamesProperty.addName(name);
});
contextMenu.getItems().add(mi);
}
if (!contextMenu.getItems().isEmpty()) {
contextMenu.getItems().add(new SeparatorMenuItem());
}
MenuItem editName = new MenuItem(bundle.getString("menu.editName"));
editName.setOnAction(value -> {
NameEditor editor = new NameEditor(selected.nameProperty().get());
String label = editor.showPopup(event.getScreenX(), event.getScreenY(), getScene().getWindow());
selected.nameProperty().set(label);
Settings.recentNamesProperty.addName(label);
});
MenuItem delete = new MenuItem(bundle.getString("menu.delete"));
delete.setOnAction(value -> deleteSelected(bundle.getString("menu.delete")));
contextMenu.getItems().addAll(editName, delete);
contextMenu.setAutoHide(true);
contextMenu.show(imageView, event.getScreenX(), event.getScreenY());
event.consume();
}
private void updateTranslatorGroupToggle() {
for (MenuItem item1 : parseMenu.getItems()) {
if (item1.getText().equals(translator.getLabel())) {
menuGroup.selectToggle((Toggle) item1);
break;
}
}
}
@FXML
private void showMainActionM(ActionEvent evt) {
MenuItem btn = (MenuItem) (evt.getSource());
String actionType;
if (btn.getText().equals("Registro de Vendas")) {
actionType = "Venda";
} else {
actionType = "Compra";
}
GUIController.getInstance().showMainActionScreen(actionType, false);
}
public MenuItem createPanelMenuItem(String panelName, String panelFilter) {
MenuItem customizedPanel = new MenuItem(panelName);
customizedPanel.setOnAction(e -> {
logger.info("Menu: Panels > Auto-create > " + panelName + "panel");
panelControl.generatePanelWithNameAndFilter(panelName, panelFilter);
panelControl.selectLastPanel();
});
return customizedPanel;
}
SelectionTableColumn() {
super("", "Include this PV when restoring values", 30, 30, false);
setCellValueFactory(new PropertyValueFactory<>("selected"));
//for those entries, which have a read-only property, disable the checkbox
setCellFactory(column -> {
TableCell<TableEntry, Boolean> cell = new CheckBoxTableCell<>(null,null);
cell.itemProperty().addListener((a, o, n) -> {
cell.getStyleClass().remove("check-box-table-cell-disabled");
TableRow<?> row = cell.getTableRow();
if (row != null) {
TableEntry item = (TableEntry) row.getItem();
if (item != null) {
cell.setEditable(!item.readOnlyProperty().get());
if (item.readOnlyProperty().get()) {
cell.getStyleClass().add("check-box-table-cell-disabled");
}
}
}
});
return cell;
});
setEditable(true);
setSortable(false);
selectAllCheckBox = new CheckBox();
selectAllCheckBox.setSelected(false);
selectAllCheckBox.setOnAction(e -> getItems().stream().filter(te -> !te.readOnlyProperty().get())
.forEach(te -> te.selectedProperty().setValue(selectAllCheckBox.isSelected())));
setGraphic(selectAllCheckBox);
MenuItem inverseMI = new MenuItem("Inverse Selection");
inverseMI.setOnAction(e -> getItems().stream().filter(te -> !te.readOnlyProperty().get())
.forEach(te -> te.selectedProperty().setValue(!te.selectedProperty().get())));
final ContextMenu contextMenu = new ContextMenu(inverseMI);
selectAllCheckBox.setOnMouseReleased(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
contextMenu.show(selectAllCheckBox, e.getScreenX(), e.getScreenY());
}
});
}
@Override
@FxThread
public void fillContextMenu(@NotNull final NodeTree<?> nodeTree,
@NotNull final ObservableList<MenuItem> items) {
items.add(new CreateVehicleWheelAction(nodeTree, this));
super.fillContextMenu(nodeTree, items);
}
@FXML
private void showMainActionM(ActionEvent evt) {
MenuItem btn = (MenuItem) (evt.getSource());
String actionType;
if (btn.getText().equals("Registro de Vendas")) {
actionType = "Venda";
} else {
actionType = "Compra";
}
GUIController.getInstance().showMainActionScreen(actionType, false);
}
@Override
public List<MenuItem> getContextMenuItems(CircuitManager circuit) {
MenuItem menuItem = new MenuItem("Edit contents");
menuItem.setOnAction(event -> {
PropertyMemoryValidator memoryValidator =
new PropertyMemoryValidator(getComponent().getAddressBits(), getComponent().getDataBits());
List<MemoryLine> memory = new ArrayList<>();
BiConsumer<Integer, Integer> listener = (address, data) -> {
int index = address / 16;
MemoryLine line = memory.get(index);
line.values.get(address - index * 16).setValue(memoryValidator.parseValue(data));
};
// Internal state can change in between and data can get out of sync
circuit.getSimulatorWindow().getSimulator().runSync(() -> {
CircuitState currentState = circuit.getCircuitBoard().getCurrentState();
memory.addAll(
memoryValidator.parse(getComponent().getMemoryContents(currentState),
(address, value) -> getComponent().store(currentState, address, value)));
getComponent().addMemoryListener(listener);
});
memoryValidator.createAndShowMemoryWindow(circuit.getSimulatorWindow().getStage(), memory);
getComponent().removeMemoryListener(listener);
});
return Collections.singletonList(menuItem);
}
private MenuItem createMenuItem(TableColumn column)
{
CheckMenuItem item = new CheckMenuItem();
boolean visible = dynamicColumnModel.isVisible(column);
item.setSelected(visible);
item.setOnAction(new MenuAction(column, visible));
return item;
}
/** Sets the field's text based on the selected items list. */
private void setFieldText(ContextMenu dropDown, List<String> selectedItems, TextField field)
{
// Handle drop down menu item checking.
for (MenuItem menuItem : dropDown.getItems())
{
CustomMenuItem custom = (CustomMenuItem) menuItem;
CheckBox check = (CheckBox) custom.getContent();
// If the item is selected make sure it is checked.
if (selectedItems.contains(check.getText()))
{
if (! check.isSelected())
check.setSelected(true);
}
// If the item is not selected, make sure it is not checked.
else
{
if (check.isSelected())
check.setSelected(false);
}
}
// Build the field text string.
String fieldText = "";
for (String item : selectedItems)
{
fieldText += (fieldText.isEmpty() ? "" : ", ") + item;
}
field.setText(fieldText);
}
public String getMenuItemText(Menu parentMenu, int index) {
MenuItem menuItem = parentMenu.getItems().get(index);
String text = menuItem.getText();
if (text == null || "".equals(text)) {
return getTextFromIcon(menuItem, index);
}
return text;
}
@Override
@FxThread
public void fillContextMenu(@NotNull final NodeTree<?> nodeTree,
@NotNull final ObservableList<MenuItem> items) {
items.add(new PlaySettingsAction(nodeTree, this));
super.fillContextMenu(nodeTree, items);
}
private MenuItem createMenuItemForDeletingTopic() {
final MenuItem deleteTopicMenuItem = new MenuItem("Delete topic");
deleteTopicMenuItem.setOnAction(event -> {
final TopicAggregatedSummary summary = topicsTableView.getSelectionModel().selectedItemProperty().get();
try {
deleteTopic(kafkaBrokerProxyProperty.get(), summary);
} catch (Exception e) {
Logger.error("Could not delete topic", e);
}
});
return deleteTopicMenuItem;
}
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();
}