JavaFX: Dynamically update Menu while showing

hanslovsky :

I would like to add a list of options to a JavaFX menu. The order of the options should be modified while the menu is showing (I will use fuzzy matching but the method for that is irrelevant for my issue). I can mimic such a behavior with CustomMenuItems that contain TextField and ListView, respectively:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MWE extends Application {

    @Override
    public void start(Stage primaryStage) {
        final Menu menu = new Menu("MENU");

        final List<String> options = Arrays.asList(
                "AbC",
                "dfjksdljf",
                "skdlfj",
                "stackoverflow");

        final StringProperty currentSelection = new SimpleStringProperty(null);

        final TextField fuzzySearchField = new TextField(null);
        final CustomMenuItem fuzzySearchItem = new CustomMenuItem(fuzzySearchField, false);
        // TODO unfortunately we seem to have to grab focus like this!
        fuzzySearchField.addEventFilter(MouseEvent.MOUSE_MOVED, e->{fuzzySearchField.requestFocus(); fuzzySearchField.selectEnd();});
        final ObservableList<String> currentMatches = FXCollections.observableArrayList();
        // just some dummy matching here
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentMatches.setAll(options.stream().filter(s -> s.toLowerCase().contains(newv)).collect(Collectors.toList())));
        final ListView<String> lv = new ListView<>(currentMatches);
        lv.addEventFilter(MouseEvent.MOUSE_MOVED, e -> lv.requestFocus());
        final CustomMenuItem lvItem = new CustomMenuItem(lv, false);
        menu.getItems().setAll(fuzzySearchItem, lvItem);
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentSelection.setValue(currentMatches.size() > 0 ? currentMatches.get(0) : null));
        fuzzySearchField.setText("");

        menu.setOnShown(e -> fuzzySearchField.requestFocus());
        final MenuButton button = new MenuButton("menu");
        button.getItems().setAll(menu);

        Platform.runLater(() -> {
            final Scene scene = new Scene(button);
            primaryStage.setScene(scene);
            primaryStage.show();
        });

    }
}

However having a ListView inside a menu structure feels strange. That's why I tried to use MenuItems instead of the ListView:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MWE2 extends Application {

    @Override
    public void start(Stage primaryStage) {
        final Menu menu = new Menu("MENU");

        final List<String> options = Arrays.asList(
                "AbC",
                "dfjksdljf",
                "skdlfj",
                "stackoverflow");

        final StringProperty currentSelection = new SimpleStringProperty(null);

        final TextField fuzzySearchField = new TextField(null);
        final CustomMenuItem fuzzySearchItem = new CustomMenuItem(fuzzySearchField, false);
        // TODO unfortunately we seem to have to grab focus like this!
        fuzzySearchField.addEventFilter(MouseEvent.MOUSE_MOVED, e->{fuzzySearchField.requestFocus(); fuzzySearchField.selectEnd();});
        final ObservableList<String> currentMatches = FXCollections.observableArrayList();
        // just some dummy matching here
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentMatches.setAll(options.stream().filter(s -> s.toLowerCase().contains(newv)).collect(Collectors.toList())));
        currentMatches.addListener((ListChangeListener<String>)change -> {
            List<MenuItem> items = new ArrayList<>();
            items.add(fuzzySearchItem);
            currentMatches.stream().map(MenuItem::new).forEach(items::add);
            System.out.println("Updating menu items!");
            menu.getItems().setAll(items);
        });
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentSelection.setValue(currentMatches.size() > 0 ? currentMatches.get(0) : null));
        fuzzySearchField.setText("");

        menu.setOnShown(e -> fuzzySearchField.requestFocus());
        final MenuButton button = new MenuButton("menu");
        button.getItems().setAll(menu);

        Platform.runLater(() -> {
            final Scene scene = new Scene(button);
            primaryStage.setScene(scene);
            primaryStage.show();
        });

    }
}

In that example, the menu does not get updated while showing, even though I can see "Updating menu items!" printed to the console, so the items of menu are being updated. The menu on the screen, however, does not change.

Is there a way of requesting a repaint of the menu?

Related questions:

hanslovsky :

I followed the suggestions by @Enigo and @Jesse_mw and used a custom node. Instead of a ListView, I decided to go with a VBox that contains only Labels because I only need basic functionality and do not want to have additional confusing handlers or highlighting. Also note that @kleopatra pointed out, that dynamic updates of items works out of the box for ContextMenu (and a potential bug in Menu), which is not an adequate choice for my use-case, unfortunately.

Here is my minimum working example code:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MWE extends Application {

    private static Label label(final String text) {
        final Label label = new Label(text);
        label.addEventFilter(MouseEvent.MOUSE_MOVED, e -> label.requestFocus());
        label.setMaxWidth(200);
        final Background background = label.getBackground();
        label.setOnMouseEntered(e -> label.setBackground(new Background(new BackgroundFill(Color.GRAY.brighter(), CornerRadii.EMPTY, Insets.EMPTY))));
        label.setOnMouseExited(e -> label.setBackground(background));
        // Do something on mouse press; in real world scenario, also hide menu
        label.setOnMousePressed(e -> {
            if (e.isPrimaryButtonDown()) {
                System.out.println(label.getText());
                e.consume();
            }
        });
        return label;
    }

    @Override
    public void start(Stage primaryStage) {
        final Menu menu = new Menu("MENU");

        final List<String> options = Arrays.asList(
                "AbC",
                "dfjksdljf",
                "skdlfj",
                "stackoverflow","ssldkfjsdaf", "sjsdlf", "apple juice", "banana", "mango", "sdlfkjasdlfjsadlfj", "lkjsdflsdfj",
                "stackoverflow","ssldkfjsdaf", "sjsdlf", "apple juice", "banana", "mango", "sdlfkjasdlfjsadlfj", "lkjsdflsdfj",
                "stackoverflowstackoverflowstackoverflowstackoverflowstackoverflowstackoverflow","ssldkfjsdaf", "sjsdlf", "apple juice", "banana", "mango", "sdlfkjasdlfjsadlfj", "lkjsdflsdfj");

        final StringProperty currentSelection = new SimpleStringProperty(null);

        final TextField fuzzySearchField = new TextField(null);
        final CustomMenuItem fuzzySearchItem = new CustomMenuItem(fuzzySearchField, false);
        fuzzySearchItem.setDisable(true);
        // TODO unfortunately we seem to have to grab focus like this!
        fuzzySearchField.addEventFilter(MouseEvent.MOUSE_MOVED, e->{fuzzySearchField.requestFocus(); fuzzySearchField.selectEnd();});
        final ObservableList<String> currentMatches = FXCollections.observableArrayList();
        // just some dummy matching here
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentMatches.setAll(options.stream().filter(s -> s.toLowerCase().contains(newv)).collect(Collectors.toList())));
        final VBox labels = new VBox();
        currentMatches.addListener((ListChangeListener<String>) change -> labels.getChildren().setAll(currentMatches.stream().map(MWE::label).collect(Collectors.toList())));
        final CustomMenuItem labelItem = new CustomMenuItem(labels, false);
        menu.getItems().setAll(fuzzySearchItem, labelItem);
        fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentSelection.setValue(currentMatches.size() > 0 ? currentMatches.get(0) : null));
        fuzzySearchField.setText("");

        menu.setOnShown(e -> fuzzySearchField.requestFocus());
        final MenuButton button = new MenuButton("menu");
        button.getItems().setAll(menu);

        Platform.runLater(() -> {
            final Scene scene = new Scene(button);
            primaryStage.setScene(scene);
            primaryStage.show();
        });

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159666&siteId=1