JavaFX:显示时动态更新菜单

问题描述 投票:2回答:2

我想在JavaFX菜单中添加一个选项列表。菜单显示时应修改选项的顺序(我将使用模糊匹配,但方法与我的问题无关)。我可以使用分别包含CustomMenuItemTextFieldListViews来模仿这种行为:

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();
        });

    }
}

但是在菜单结构中有一个ListView感觉很奇怪。这就是为什么我试图使用MenuItems而不是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();
        });

    }
}

在该示例中,菜单在显示时不会更新,即使我可以看到"Updating menu items!"打印到控制台,因此menu的项目正在更新。但是,屏幕上的菜单不会改变。

有没有办法要求重新绘制菜单?

相关问题:

java listview javafx menu javafx-8
2个回答
1
投票

我按照@Enigo@Jesse_mw的建议,使用了一个自定义节点。而不是ListView,我决定使用仅包含VBoxs的Label,因为我只需要基本功能,并且不希望有其他令人困惑的处理程序或突出显示。另请注意,@kleopatra指出,dynamic updates of items works out of the box for ContextMenu (and a potential bug in Menu),不幸的是,它不适合我的用例。

这是我的最低工作示例代码:

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();
        });

    }
}

0
投票

要在JavaFX中动态更新列表,可以使用Binding和可观察列表,就像我在代码中所做的那样。以下代码的唯一问题是,由于Menu类的功能,它将无法正常工作,每次更新列表时菜单都会隐藏。我认为您应该像注释中讨论的那样设置列表视图,并再次使用以下绑定,因为它适用于所有使用Observable Lists的视图我相信。

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
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.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.lang.management.PlatformManagedObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MWE2 extends Application {
public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {
    final Menu menu = new Menu("MENU");
    final MenuButton button = new MenuButton("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()));

    });
   //changed from ArrayList to ObservableArray
    ObservableList<MenuItem> items =  FXCollections.observableArrayList(); 
    currentMatches.addListener((ListChangeListener<String>) change -> {
        items.clear();//Clearing items to in-case of duplicates and NULL duplicates.
        items.add(fuzzySearchItem);

        currentMatches.stream().map(MenuItem::new).forEach(items::add);

        System.out.println("Updating menu items!");
        menu.getItems().setAll(items);


    });
    // Binding to Observable items.
    Bindings.bindContent(menu.getItems(), items); 
    fuzzySearchField.textProperty().addListener((obs, oldv, newv) -> currentSelection.setValue(currentMatches.size() > 0 ? currentMatches.get(0) : null));
    fuzzySearchField.setText("");


    button.getItems().setAll(menu);


    final Scene scene = new Scene(button);

    primaryStage.setScene(scene);
    primaryStage.show();

}

}

© www.soinside.com 2019 - 2024. All rights reserved.