看看这个简单的应用程序:
按下文本字段上的ctrl + space,listView出现焦点,您可以使用箭头键进行选择。但是如果你将鼠标移到listView上,则customMenuItem会获得悬停突出显示并且listview松散焦点,箭头键不再起作用
我如何专注于listview?
import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.geometry.Side; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.CustomMenuItem; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.HBox; import javafx.stage.Stage;public class Main extends Application { @Override public void start(Stage primaryStage) { try { HBox root = new HBox(new SuggestionTextFiedl());
Scene scene = new Scene(root, 400, 400); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } public class SuggestionTextFiedl extends TextField { ListView<String> lv = new ListView<>(); CustomMenuItem lvContainer = new CustomMenuItem(lv); ContextMenu contextMenu = new ContextMenu(lvContainer); public SuggestionTextFiedl() { super(); List<String> content = new ArrayList<>(); content.add("item1"); content.add("item2"); content.add("item3"); content.add("item1"); content.add("item2"); content.add("item3"); lv.setItems(FXCollections.observableList(content)); lv.setPrefWidth(100); lv.setPrefHeight(100); this.addEventHandler(KeyEvent.KEY_RELEASED, e -> { if (e.getCode().equals(KeyCode.SPACE) && e.isControlDown()) { System.out.println("ici"); contextMenu.show(SuggestionTextFiedl.this, Side.BOTTOM, 0, 0); lv.requestFocus(); } }); } } }
答案 0 :(得分:0)
我的解决方案不确定这是正确的方法
contextMenu.addEventFilter(MouseEvent.MOUSE_ENTERED_TARGET, e -> {
e.consume();
});