JavaFX ChoiceBox基于键盘输入选择对应条目功能失效问题咨询
问题根因
OpenJFX官方文档约定的ChoiceBox选中状态下字母数字键跳转功能,并未在默认控件实现中内置,属于功能缺失,需要手动扩展实现。
修复方案
给ChoiceBox添加键盘按下事件监听器,维护输入的字符序列,匹配列表项后跳转选中,修改后的核心代码如下:
package com.techniqab.testchoicebox; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.layout.Pane; import javafx.stage.Stage; import java.net.URL; import java.nio.file.Paths; import java.util.concurrent.atomic.AtomicLong; public class TestchoiceboxApplication extends Application { @Override public void start(Stage primaryStage) throws Exception{ URL url = Paths.get("./src/main/resources/sample.fxml").toUri().toURL(); Parent root = FXMLLoader.load(url); primaryStage.setTitle("Hello World"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); var cb = new ChoiceBox(); cb.getItems().addAll("a", "b", "test1", "test2", "demo"); // 新增键盘匹配逻辑 StringBuilder inputBuffer = new StringBuilder(); // 连续输入超时阈值 单位:毫秒,超时后清空输入序列 long timeout = 1000; AtomicLong lastInputTime = new AtomicLong(System.currentTimeMillis()); cb.setOnKeyPressed(event -> { String character = event.getText(); // 仅处理字母数字输入 if (character.matches("[a-zA-Z0-9]")) { long currentTime = System.currentTimeMillis(); if (currentTime - lastInputTime.get() > timeout) { inputBuffer.setLength(0); } inputBuffer.append(character.toLowerCase()); lastInputTime.set(currentTime); String prefix = inputBuffer.toString(); for (Object item : cb.getItems()) { String itemStr = item.toString().toLowerCase(); if (itemStr.startsWith(prefix)) { cb.getSelectionModel().select(item); break; } } event.consume(); } }); ((Pane) root).getChildren().add(cb); } public static void main(String[] args) { launch(args); } }
替代方案
如果没有强制使用ChoiceBox的需求,可以直接替换为ComboBox控件,该控件默认已经实现了文档约定的键盘首字符匹配跳转功能,无需额外编码。
内容的提问来源于stack exchange,提问作者Techniquab
相关产品推荐
相关产品推荐

