下面列出了怎么用javafx.scene.control.ContextMenu的API类实例代码及写法,或者点击链接到github查看源代码。
public void onViewMemory(Event event) {
// if (memoryStage == null) {
// memoryStage = FxUtils.newStage(null, "内存查看",
// "memory.fxml", "main.css");
// }
// memoryStage.show();
// memoryStage.toFront();
if (machine.getRomFile() == null) {
onViewRAM(event);
} else {
MenuItem ramViewItem = new MenuItem("查看RAM");
ramViewItem.setOnAction(event1 -> onViewRAM(event1));
MenuItem romViewItem = new MenuItem("查看ROM");
romViewItem.setOnAction(event1 -> onViewROM(event1));
new ContextMenu(ramViewItem, romViewItem).show(memoryButton, Side.TOP, 0, 0);
}
}
@SneakyThrows
private CompletableFuture<Optional<RequestTypePlugin>> getRequestTypePluginQuick(Node node) {
List<RequestTypePlugin> requestTypePlugins = plugins.loadRequestTypePlugins();
if (requestTypePlugins.size() == 0)
throw new IllegalArgumentException("No RequestType plugins found");
ContextMenu ctxMenu = new ContextMenu();
CompletableFuture<RequestTypePlugin> f = new CompletableFuture<RequestTypePlugin>();
requestTypePlugins.forEach(rtp -> {
var itm = new MenuItem(rtp.getRequestType());
itm.setOnAction(e -> {
f.complete(rtp);
});
ctxMenu.getItems().add(itm);
});
ctxMenu.setOnCloseRequest(e -> f.complete(null));
Point location = MouseInfo.getPointerInfo().getLocation();
ctxMenu.show(node, location.getX(), location.getY());
return f.thenApply(Optional::ofNullable);
}
private void initTopSectionContextMenu(ContextMenu contextMenu, boolean hasRanges) {
MenuItem setDestinationItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Set destination"),
MaterialDesignIcon.AIRPLANE_LANDING);
setDestinationItem.setOnAction(e -> eventStudio().broadcast(
requestDestination(getSelectionModel().getSelectedItem().descriptor().getFile(), getOwnerModule()),
getOwnerModule()));
setDestinationItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.ALT_DOWN));
selectionChangedConsumer = e -> setDestinationItem.setDisable(!e.isSingleSelection());
contextMenu.getItems().add(setDestinationItem);
if (hasRanges) {
MenuItem setPageRangesItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Set as range for all"),
MaterialDesignIcon.FORMAT_INDENT_INCREASE);
setPageRangesItem.setOnAction(e -> eventStudio().broadcast(
new SetPageRangesRequest(getSelectionModel().getSelectedItem().pageSelection.get()),
getOwnerModule()));
setPageRangesItem.setAccelerator(new KeyCodeCombination(KeyCode.R, KeyCombination.CONTROL_DOWN));
selectionChangedConsumer = selectionChangedConsumer
.andThen(e -> setPageRangesItem.setDisable(!e.isSingleSelection()));
contextMenu.getItems().add(setPageRangesItem);
}
contextMenu.getItems().add(new SeparatorMenuItem());
}
private void handleVariableType(VariableSelection selection) {
ContextMenu menu = new ContextMenu();
Menu refs = new Menu(LangUtil.translate("ui.edit.method.referrers"));
for (AST ast : root.getChildren()) {
if (ast instanceof VarInsnAST && ((VarInsnAST) ast).getVariableName().getName().equals(selection.name)) {
MenuItem ref = new ActionMenuItem(ast.getLine() + ": " + ast.print(), () -> {
int line = ast.getLine() - 1;
codeArea.moveTo(line, 0);
codeArea.requestFollowCaret();
});
refs.getItems().add(ref);
}
}
if (refs.getItems().isEmpty())
refs.setDisable(true);
menu.getItems().add(refs);
codeArea.setContextMenu(menu);
}
private void createContextMenu(WebView webView) {
ContextMenu contextMenu = new ContextMenu();
MenuItem reload = new MenuItem("Reload");
reload.setOnAction(e -> webView.getEngine().reload());
MenuItem savePage = new MenuItem("Save Page");
savePage.setOnAction(e -> System.out.println("Save page..."));
MenuItem hideImages = new MenuItem("Hide Images");
hideImages.setOnAction(e -> System.out.println("Hide Images..."));
contextMenu.getItems().addAll(reload, savePage, hideImages);
webView.setOnMousePressed(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
contextMenu.show(webView, e.getScreenX(), e.getScreenY());
} else {
contextMenu.hide();
}
});
}
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");
}
/**
* Provide a callback that sets the given context menu on each cell, if and
* only if the constraint given passes. If the constraint is null, it will
* always pass.
* <p/>
* @param <T> the generic type of the cell.
* @param contextMenu the context menu to show.
* @param cellFactory the cell factory to use.
* @param constraint the constraint placed on showing the context menu - it
* will only be shown if this constraint passes, or it is null.
* @return a callback that sets the given context menu on each cell.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(final ContextMenu contextMenu, final Callback<ListView<T>, ListCell<T>> cellFactory,
final Constraint<T> constraint) {
return new Callback<ListView<T>, ListCell<T>>() {
@Override
public ListCell<T> call(ListView<T> listView) {
final ListCell<T> cell = cellFactory == null ? new DefaultListCell<T>() : cellFactory.call(listView);
cell.itemProperty().addListener(new ChangeListener<T>() {
@Override
public void changed(ObservableValue<? extends T> ov, T oldVal, T newVal) {
if(newVal == null || (constraint != null && !constraint.isTrue(newVal))) {
cell.setContextMenu(null);
}
else {
cell.setContextMenu(contextMenu);
}
}
});
return cell;
}
};
}
private void handleJumpType(JumpSelection selection) {
ContextMenu menu = new ContextMenu();
MenuItem jump = new ActionMenuItem(LangUtil.translate("ui.edit.method.follow"), () -> {
for (AST ast : root.getChildren()) {
if (ast instanceof LabelAST) {
String name = ((LabelAST) ast).getName().getName();
if(name.equals(selection.destination)) {
int line = ast.getLine() - 1;
codeArea.moveTo(line, 0);
codeArea.requestFollowCaret();
}
}
}
});
menu.getItems().add(jump);
codeArea.setContextMenu(menu);
}
private void handleLabelType(LabelSelection selection) {
ContextMenu menu = new ContextMenu();
Menu refs = new Menu(LangUtil.translate("ui.edit.method.referrers"));
for (AST ast : root.getChildren()) {
if ((ast instanceof FlowController && ((FlowController) ast).targets().contains(selection.name)) ||
(ast instanceof LineInsnAST && ((LineInsnAST) ast).getLabel().getName().equals(selection.name))) {
MenuItem ref = new ActionMenuItem(ast.getLine() + ": " + ast.print(), () -> {
int line = ast.getLine() - 1;
codeArea.moveTo(line, 0);
codeArea.requestFollowCaret();
});
refs.getItems().add(ref);
}
}
if (refs.getItems().isEmpty())
refs.setDisable(true);
menu.getItems().add(refs);
codeArea.setContextMenu(menu);
}
public ChartContainerController(String selectedType, IntegerProperty interval) {
Initialization.initializeFXML(this, "/fxml/dashboard/charts/ChartContainer.fxml");
this.interval = interval;
chartType = new SimpleStringProperty();
chartType.addListener(this::handleChartTypeChanged);
chartType.set(selectedType);
contextMenu = new ContextMenu();
contextMenu.getItems().addAll(
createContextMenuItem(ChartsFactory.ChartTypes.TX_PPS),
createContextMenuItem(ChartsFactory.ChartTypes.RX_PPS),
createContextMenuItem(ChartsFactory.ChartTypes.TX_BPS_L1),
createContextMenuItem(ChartsFactory.ChartTypes.TX_BPS_L2),
createContextMenuItem(ChartsFactory.ChartTypes.RX_BPS_L2),
createContextMenuItem(ChartsFactory.ChartTypes.PACKET_LOSS),
new SeparatorMenuItem(),
createContextMenuItem(ChartsFactory.ChartTypes.MAX_LATENCY, runningConfiguration.latencyEnabledProperty()),
createContextMenuItem(ChartsFactory.ChartTypes.AVG_LATENCY, runningConfiguration.latencyEnabledProperty()),
createContextMenuItem(ChartsFactory.ChartTypes.JITTER_LATENCY, runningConfiguration.latencyEnabledProperty()),
createContextMenuItem(ChartsFactory.ChartTypes.TEMPORARY_MAX_LATENCY, runningConfiguration.latencyEnabledProperty()),
createContextMenuItem(ChartsFactory.ChartTypes.LATENCY_HISTOGRAM, runningConfiguration.latencyEnabledProperty())
);
}
private void bindPopupMenuToSelectedRow(KafkaClusterProxy proxy, TableRow<TopicAggregatedSummary> row) {
final MenuItem deleteTopicMenuItem = createMenuItemForDeletingTopic();
final MenuItem createTopicMenuItem = createMenuItemForCreatingNewTopic();
final MenuItem alterTopicMenuItem = createMenuItemForAlteringTopic();
final MenuItem topicPropertiesMenuItem = createMenuItemForShowingTopicProperties();
final ContextMenu contextMenu = getTopicManagementContextMenu(deleteTopicMenuItem,
createTopicMenuItem,
alterTopicMenuItem,
topicPropertiesMenuItem);
row.contextMenuProperty().bind(new ReadOnlyObjectWrapper<>(contextMenu));
topicPropertiesMenuItem.disableProperty().bind(row.emptyProperty());
if (proxy.isTopicDeletionEnabled() != TriStateConfigEntryValue.True) {
deleteTopicMenuItem.setText("Delete topic (disabled by broker)");
deleteTopicMenuItem.disableProperty().setValue(true);
} else {
deleteTopicMenuItem.disableProperty().bind(row.emptyProperty());
}
alterTopicMenuItem.disableProperty().bind(row.emptyProperty());
}
@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 void createContextMenu()
{
final ContextMenu menu = new ContextMenu();
tree_view.setOnContextMenuRequested(event ->
{
menu.getItems().clear();
if (ContextMenuHelper.addSupportedEntries(tree_view, menu))
menu.getItems().add(new SeparatorMenuItem());
menu.getItems().add(new PrintAction(tree_view));
menu.getItems().add(new SaveSnapshotAction(tree_view));
menu.getItems().add(new SendEmailAction(tree_view, "PV Snapshot", () -> "See attached screenshot.", () -> Screenshot.imageFromNode(tree_view)));
menu.getItems().add(new SendLogbookAction(tree_view, "PV Snapshot", () -> "See attached screenshot.", () -> Screenshot.imageFromNode(tree_view)));
menu.show(tree_view.getScene().getWindow(), event.getScreenX(), event.getScreenY());
});
tree_view.setContextMenu(menu);
}
private void createContextMenu()
{
final ContextMenu menu = new ContextMenu();
plot.setOnContextMenuRequested(event ->
{
menu.getItems().setAll(new ToggleToolbarMenuItem(plot));
final List<Trace<Double>> traces = new ArrayList<>();
plot.getTraces().forEach(traces::add);
if (! traces.isEmpty())
menu.getItems().add(new ToggleLinesMenuItem(plot, traces));
menu.getItems().addAll(new SeparatorMenuItem(),
new PrintAction(plot),
new SaveSnapshotAction(plot));
menu.show(getScene().getWindow(), event.getScreenX(), event.getScreenY());
});
}
private void updateContextMenu(final ContextMenuEvent event)
{
final ContextMenu menu = channel_table.getContextMenu();
final List<ChannelInfo> selection = channel_table.getSelectionModel().getSelectedItems();
if (selection.isEmpty())
menu.getItems().clear();
else
{
menu.getItems().setAll(new AddToPlotAction(channel_table, model, undo, selection),
new SeparatorMenuItem());
SelectionService.getInstance().setSelection(channel_table, selection);
ContextMenuHelper.addSupportedEntries(channel_table, menu);
menu.show(channel_table.getScene().getWindow(), event.getScreenX(), event.getScreenY());
}
}
private void createContextMenu()
{
final MenuItem add_axis = new MenuItem(Messages.AddAxis, Activator.getIcon("add"));
add_axis.setOnAction(event -> new AddAxisCommand(undo, model));
final ContextMenu menu = new ContextMenu();
axes_table.setOnContextMenuRequested(event ->
{
final ObservableList<MenuItem> items = menu.getItems();
items.setAll(add_axis);
final List<AxisConfig> selection = axes_table.getSelectionModel().getSelectedItems();
if (selection.size() > 0)
items.add(new DeleteAxes(axes_table, model, undo, selection));
if (model.getEmptyAxis().isPresent())
items.add(new RemoveUnusedAxes(model, undo));
menu.show(axes_table.getScene().getWindow(), event.getScreenX(), event.getScreenY());
});
}
private void createContextMenu()
{
// Publish selected items as PV
final ListChangeListener<PVInfo> sel_changed = change ->
{
final List<ProcessVariable> pvs = change.getList()
.stream()
.map(info -> new ProcessVariable(info.name.get()))
.collect(Collectors.toList());
SelectionService.getInstance().setSelection(PVListApplication.DISPLAY_NAME, pvs);
};
table.getSelectionModel().getSelectedItems().addListener(sel_changed);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// Context menu with selection-based entries, i.e. PV contributions
final ContextMenu menu = new ContextMenu();
table.setOnContextMenuRequested(event ->
{
menu.getItems().clear();
ContextMenuHelper.addSupportedEntries(table, menu);
menu.show(table.getScene().getWindow());
});
table.setContextMenu(menu);
}
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();
}
public final void initializeEventTable(){
eventTable = new TableView<>();
eventTable.setItems(eventList.observableList);
UIUtils.setSize(eventTable, Main.columnWidthRIGHT, 247);
TableColumn textualDescription = new TableColumn("Textual desc.");
textualDescription.setMinWidth(Main.columnWidthRIGHT/2);
TableColumn temporalDescription = new TableColumn("Temporal desc.");
temporalDescription.setMinWidth(Main.columnWidthRIGHT/2-1);
textualDescription.setCellValueFactory(new PropertyValueFactory<>("textualDescription"));
temporalDescription.setCellValueFactory(new PropertyValueFactory<>("temporalDescription"));
EventTableContextMenu tableCellFactory = new EventTableContextMenu(createSelectedEventHandler(), new ContextMenu());
textualDescription.setCellFactory(tableCellFactory);
eventTable.getColumns().addAll(textualDescription,temporalDescription);
}
/**
* Hides the area's context menu if it is not {@code null} and it is {@link ContextMenu#isShowing() showing}.
*/
default void hideContextMenu() {
ContextMenu menu = getContextMenu();
if (menu != null && menu.isShowing()) {
menu.hide();
}
}
public MassListComponent() {
setHgap(5.0);
lookupMenu = new ContextMenu();
nameField = new TextField();
nameField.setPrefColumnCount(15);
lookupButton = new Button("Choose...");
lookupButton.setOnAction(e -> {
List<String> currentNames = getMassListNames();
lookupMenu.getItems().clear();
for (String name : currentNames) {
MenuItem item = new MenuItem(name);
item.setOnAction(e2 -> {
nameField.setText(name);
});
lookupMenu.getItems().add(item);
}
final Bounds boundsInScreen = lookupButton.localToScreen(lookupButton.getBoundsInLocal());
lookupMenu.show(lookupButton, boundsInScreen.getCenterX(), boundsInScreen.getCenterY());
// lookupMenu.show(lookupButton, 0, 0);
});
getChildren().addAll(nameField, lookupButton);
}
public static void getDirectoryMenu(HBox fileIcon, String fileName, MouseEvent e, ClientObject client) {
ContextMenu cm = new ContextMenu();
MenuItem sb2 = new MenuItem("Open Folder");
sb2.setOnAction(event -> {
try {
client.clientCommunicate("CHNGDIR");
DataOutputStream dos = new DataOutputStream(client.getClient().getOutputStream());
dos.writeUTF(fileName);
} catch (IOException e1) {
Logger.log(Level.ERROR, e1.toString());
}
});
cm.getItems().addAll(sb2);
cm.show(fileIcon, e.getScreenX(), e.getScreenY());
}
public void setContextMenu(ContextMenu contextMenu) {
this.contextMenu = contextMenu;
Platform.runLater(new Runnable() {
@Override
public void run() {
if (null == contextMenu) {
if (OnlyTrayIcon.this.contextMenu != null) {
OnlyTrayIcon.this.contextMenu.showingProperty().removeListener(listener);
}
} else {
contextMenu.showingProperty().addListener(listener);
}
}
});
}
public OnlyContextMenuSkin(ContextMenu popupMenu) {
super(popupMenu);
Node node = super.getNode();
if (node instanceof Region) {
Region root = (Region) node;
root.setPadding(new Insets(8, 0, 8, 0));
}
}
private static Menu matcherAsMenu(
final String menuText,
final List<String> candidates,
final Consumer<String> processSelection) {
final Menu menu = new Menu(menuText);
final Consumer<String> hideAndProcess = selection -> {
menu.getParentMenu();
menu.hide();
for (Menu m = menu.getParentMenu(); m != null; m = m.getParentMenu())
m.hide();
Optional.ofNullable(menu.getParentPopup()).ifPresent(ContextMenu::hide);
processSelection.accept(selection);
};
final MatchSelection matcher = MatchSelection.fuzzySorted(candidates, hideAndProcess);
matcher.setMaxWidth(400);
final CustomMenuItem cmi = new CustomMenuItem(matcher, false);
menu.setOnShowing(e -> {Platform.runLater(matcher::requestFocus);});
// clear style to avoid weird blue highlight
cmi.getStyleClass().clear();
menu.getItems().setAll(cmi);
return menu;
}
public Optional<ContextMenu> getContextMenu(
String menuText,
PainteraBaseView viewer,
Supplier<String> projectDirectory,
Consumer<Exception> exceptionHandler)
{
try {
return Optional.of(getContextMenu(menuText, viewer, projectDirectory));
} catch (InstantiableException e) {
exceptionHandler.accept(e);
return Optional.empty();
}
}
public ContextMenu getContextMenu(
String menuText,
PainteraBaseView viewer,
Supplier<String> projectDirectory) throws InstantiableException
{
List<Pair<String, Consumer<ActionEvent>>> asConsumers = new ArrayList<>();
final List<Pair<String, BiConsumer<PainteraBaseView, Supplier<String>>>> handlers = new ArrayList<>(getMenuEntries());
for (Pair<String, BiConsumer<PainteraBaseView, Supplier<String>>> handler : handlers)
{
Consumer<ActionEvent> consumer = event -> handler.getValue().accept(viewer, projectDirectory);
asConsumers.add(new Pair<>(handler.getKey(), consumer));
}
return new MenuFromHandlers(asConsumers).asContextMenu(menuText);
}
/**
* Clicks on menu item with target text
* @param menu
* @param target
*/
public void clickMenuItem(ContextMenu menu, String target) {
menu.getItems()
.stream()
.filter(item -> item.getText().equals(target))
.findFirst().ifPresent(item -> {
Platform.runLater(item::fire);
});
}
private void addAdditionalEntryToConfigNameContextMenu() {
TextFieldSkin customContextSkin = new TextFieldSkin(topicConfigNameField) {
@Override
public void populateContextMenu(ContextMenu contextMenu) {
super.populateContextMenu(contextMenu);
contextMenu.getItems().add(0, new SeparatorMenuItem());
contextMenu.getItems().add(0, generateNameMenuItem);
}
};
topicConfigNameField.setSkin(customContextSkin);
}
private void addAdditionalEntryToConfigNameContextMenu() {
TextFieldSkin customContextSkin = new TextFieldSkin(messageNameTextField) {
@Override
public void populateContextMenu(ContextMenu contextMenu) {
super.populateContextMenu(contextMenu);
contextMenu.getItems().add(0, new SeparatorMenuItem());
contextMenu.getItems().add(0, generateNameMenuItem);
}
};
messageNameTextField.setSkin(customContextSkin);
}