下面列出了怎么用javafx.scene.control.CustomMenuItem的API类实例代码及写法,或者点击链接到github查看源代码。
private ContextMenu buildContextMenu(Node item) {
ContextMenu contextMenu = new ContextMenuWithNoArrows();
CustomMenuItem menuItem = new CustomMenuItem(new Label("Export subtree...",
new FontIcon("fas-external-link-alt")));
Tooltip tooltip = new Tooltip("Export subtree to a text format");
Tooltip.install(menuItem.getContent(), tooltip);
menuItem.setOnAction(
e -> getService(DesignerRoot.TREE_EXPORT_WIZARD).apply(x -> x.showYourself(x.bindToNode(item)))
);
contextMenu.getItems().add(menuItem);
return contextMenu;
}
private void populatePopup(List<String> searchResult) {
List<CustomMenuItem> menuItems = new LinkedList<>();
int count = Math.min(searchResult.size(), maxEntries);
for (int i = 0; i < count; i++) {
final String result = searchResult.get(i);
Label entryLabel = new Label(result);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
item.setOnAction(actionEvent -> {
setText(result);
entriesPopup.hide();
});
menuItems.add(item);
}
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
}
/**
* Populate the entry set with the given search results. Display is limited
* to 10 entries, for performance.
*
* @param searchResult
* The set of matching strings.
*/
private void populatePopup(List<String> searchResult) {
List<CustomMenuItem> menuItems = new LinkedList<>();
// If you'd like more entries, modify this line.
int maxEntries = 10;
int count = Math.min(searchResult.size(), maxEntries);
for (int i = 0; i < count; i++) {
final String result = searchResult.get(i);
Label entryLabel = new Label(result);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
item.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
setText(result);
entriesPopup.hide();
}
});
menuItems.add(item);
}
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
}
private CustomMenuItem getColumnVisibility(ThreeTuple<String, Attribute, TableColumn<ObservableList<String>, String>> columnTuple) {
final CheckBox columnCheckbox = new CheckBox(columnTuple.getThird().getText());
columnCheckbox.selectedProperty().bindBidirectional(columnTuple.getThird().visibleProperty());
columnCheckbox.setOnAction(e -> {
updateVisibleColumns(parent.getCurrentGraph(), parent.getCurrentState(), Arrays.asList(columnTuple),
((CheckBox) e.getSource()).isSelected() ? UpdateMethod.ADD : UpdateMethod.REMOVE);
e.consume();
});
final CustomMenuItem columnVisibility = new CustomMenuItem(columnCheckbox);
columnVisibility.setHideOnClick(false);
columnVisibility.setId(columnTuple.getThird().getText());
return columnVisibility;
}
private void updateRecentFilesMenu() {
List<MenuItem> items = new ArrayList<>();
List<File> filesToClear = new ArrayList<>();
for (final File f : recentFiles) {
if (f.exists() && f.isFile()) {
CustomMenuItem item = new CustomMenuItem(new Label(f.getName()));
item.setOnAction(e -> loadSourceFromFile(f));
item.setMnemonicParsing(false);
Tooltip.install(item.getContent(), new Tooltip(f.getAbsolutePath()));
items.add(item);
} else {
filesToClear.add(f);
}
}
recentFiles.removeAll(filesToClear);
if (items.isEmpty()) {
openRecentMenu.setDisable(true);
return;
}
Collections.reverse(items);
items.add(new SeparatorMenuItem());
MenuItem clearItem = new MenuItem();
clearItem.setText("Clear menu");
clearItem.setOnAction(e -> {
recentFiles.clear();
openRecentMenu.setDisable(true);
});
items.add(clearItem);
openRecentMenu.getItems().setAll(items);
}
private void showAutocompletePopup(int insertionIndex, String input) {
CompletionResultSource suggestionMaker = mySuggestionProvider.get();
List<MenuItem> suggestions =
suggestionMaker.getSortedMatches(input, 5)
.map(result -> {
Label entryLabel = new Label();
entryLabel.setGraphic(result.getTextFlow());
entryLabel.setPrefHeight(5);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
item.setUserData(result);
item.setOnAction(e -> applySuggestion(insertionIndex, input, result.getStringMatch()));
return item;
})
.collect(Collectors.toList());
autoCompletePopup.getItems().setAll(suggestions);
myCodeArea.getCharacterBoundsOnScreen(insertionIndex, insertionIndex + input.length())
.ifPresent(bounds -> autoCompletePopup.show(myCodeArea, bounds.getMinX(), bounds.getMaxY()));
Skin<?> skin = autoCompletePopup.getSkin();
if (skin != null) {
Node fstItem = skin.getNode().lookup(".menu-item");
if (fstItem != null) {
fstItem.requestFocus();
}
}
}
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;
}
/**
* Add a new CheckMenuItem to the drop down ContextMenu.
* @param item - Item to be added.
*/
private void addToLogbookDropDown(String item)
{
CheckBox checkBox = new CheckBox(item);
CustomMenuItem newLogbook = new CustomMenuItem(checkBox);
newLogbook.setHideOnClick(false);
checkBox.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
CheckBox source = (CheckBox) e.getSource();
String text = source.getText();
if (source.isSelected())
{
if (! model.hasSelectedLogbook(text))
{
model.addSelectedLogbook(text);
}
setFieldText(logbookDropDown, model.getSelectedLogbooks(), logbookField);
}
else
{
model.removeSelectedLogbook(text);
setFieldText(logbookDropDown, model.getSelectedLogbooks(), logbookField);
}
}
});
if (model.hasSelectedLogbook(item))
checkBox.fire();
logbookDropDown.getItems().add(newLogbook);
}
/**
* Add a new CheckMenuItem to the drop down ContextMenu.
* @param item - Item to be added.
*/
private void addToTagDropDown(String item)
{
CheckBox checkBox = new CheckBox(item);
CustomMenuItem newTag = new CustomMenuItem(checkBox);
newTag.setHideOnClick(false);
checkBox.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
CheckBox source = (CheckBox) e.getSource();
String text = source.getText();
if (source.isSelected())
{
if (! model.hasSelectedTag(text))
{
model.addSelectedTag(text);
}
setFieldText(tagDropDown, model.getSelectedTags(), tagField);
}
else
{
model.removeSelectedTag(text);
setFieldText(tagDropDown, model.getSelectedTags(), tagField);
}
}
});
if (model.hasSelectedTag(item))
checkBox.fire();
tagDropDown.getItems().add(newTag);
}
/** 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);
}
private Node create(final URI input) throws Exception
{
final String[] parsed = AlarmURI.parseAlarmURI(input);
server = parsed[0];
config_name = parsed[1];
try
{
client = new AlarmClient(server, config_name);
final AlarmAreaView area_view = new AlarmAreaView(client);
client.start();
if (AlarmSystem.config_names.size() > 0)
{
final AlarmConfigSelector select = new AlarmConfigSelector(config_name, new_config_name ->
{
// CustomMenuItem configured to stay open to allow selection.
// Once selected, do close the menu.
area_view.getMenu().hide();
changeConfig(new_config_name);
});
final CustomMenuItem select_item = new CustomMenuItem(select, false);
area_view.getMenu().getItems().add(0, select_item);
}
return area_view;
}
catch (final Exception ex)
{
logger.log(Level.WARNING, "Cannot create alarm area panel for " + input, ex);
return new Label("Cannot create alarm area panel for " + input);
}
}
/** @param options Options to offer in the drop-down */
public void setOptions(final Collection<T> options)
{
selection.clear();
getItems().clear();
// Could use CheckMenuItem instead of CheckBox-in-CustomMenuItem,
// but that adds/removes a check mark.
// When _not_ selected, there's just an empty space, not
// immediately obvious that item _can_ be selected.
// Adding/removing one CheckMenuItem closes the drop-down,
// while this approach allows it to stay open.
for (T item : options)
{
final CheckBox checkbox = new CheckBox(item.toString());
checkbox.setUserData(item);
checkbox.setOnAction(event ->
{
if (checkbox.isSelected())
selection.add(item);
else
selection.remove(item);
});
final CustomMenuItem menuitem = new CustomMenuItem(checkbox);
menuitem.setHideOnClick(false);
getItems().add(menuitem);
}
}
/** Programmatically select options
*
* <p>Options must be one of those provided in previous
* call to <code>setOptions</code>.
* Will trigger listeners to the <code>selectedOptions</code>.
*
* @param options Options to select
*/
public void selectOptions(final Collection<T> options)
{
selection.clear();
selection.addAll(options);
for (MenuItem mi : getItems())
{
final CheckBox checkbox = (CheckBox) ((CustomMenuItem)mi).getContent();
checkbox.setSelected(selection.contains(checkbox.getUserData()));
}
}
CustomMenuItem getSuggestion(String suggestion) {
Label entryLabel = new Label(suggestion);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
item.setOnAction(f -> {
addPrincipal.setText(suggestion);
});
return item;
}
public CustomizedTreeCell(IFileEventManager fileEventManager,
Provider<IFileRecoveryHandler> recoverFileHandlerProvider,
Provider<IShareFolderHandler> shareFolderHandlerProvider,
Provider<IForceSyncHandler> forceSyncHandlerProvider){
this.fileEventManager = fileEventManager;
this.shareFolderHandlerProvider = shareFolderHandlerProvider;
this.recoverFileHandlerProvider = recoverFileHandlerProvider;
this.forceSyncHandlerProvider = forceSyncHandlerProvider;
menu = new ContextMenu();
deleteItem = new CustomMenuItem(new Label("Delete from network"));
deleteItem.setOnAction(new DeleteAction());
menu.getItems().add(deleteItem);
shareItem = new CustomMenuItem(new Label("Share"));
shareItem.setOnAction(new ShareFolderAction());
menu.getItems().add(shareItem);
propertiesItem = new MenuItem("Properties");
propertiesItem.setOnAction(new ShowPropertiesAction());
menu.getItems().add(propertiesItem);
forceSyncItem = new MenuItem("Force synchronization");
forceSyncItem.setOnAction(new ForceSyncAction());
menu.getItems().add(forceSyncItem);
recoverMenuItem = createRecoveMenuItem();
menu.getItems().add(recoverMenuItem);
menu.setOnShowing(new ShowMenuHandler());
setContextMenu(menu);
}
private void addItems(int items) {
for (int i = 0; i < items; i++) {
itemsLst.add(new CustomMenuItem(new Label("New Item " + itemsCount++)));
customToolbarItem.getItems().add(itemsLst.get(itemsLst.size() - 1));
}
}
private MenuItem createRecoveMenuItem() {
Label label = new Label("Recover File");
MenuItem menuItem = new CustomMenuItem(label);
menuItem.setOnAction(new RecoverFileAction());
return menuItem;
}
/**
* @param event
* @return text content from an event's source
*/
public static Optional<String> getTextOnAction(ActionEvent event) {
return Optional.of(((CustomMenuItem) event.getSource()).getText());
}