【问题标题】:How to remove selection on input in editable ComboBox如何删除可编辑组合框中的输入选择
【发布时间】:2015-12-13 02:30:17
【问题描述】:

是的,早先有 threadsguides 在这个问题上。他们告诉我setValue(null)getSelectionModel().clearSelection() 应该是答案。但是做任何这些都会给我一个java.lang.IndexOutOfBoundsException

我想要做的是每次将某些内容写入组合框中时清除选择。这是因为当您在组合框中编写某些内容并且在组合框弹出窗口中保持选中其他内容时,它会导致问题并且看起来很奇怪。

这是一个 SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;

import javafx.stage.Stage;
import javafx.util.converter.IntegerStringConverter;

public class SSCCE extends Application {

    @Override
    public void start(Stage stage) {

        HBox root = new HBox();

        ComboBox<Integer> cb = new ComboBox<Integer>();
        cb.setEditable(true);
        cb.getItems().addAll(1, 2, 6, 7, 9);
        cb.setConverter(new IntegerStringConverter());

        cb.getEditor().textProperty()
                .addListener((obs, oldValue, newValue) -> {
                    // Using any of these will give me a IndexOutOfBoundsException
                    // Using any of these will give me a IndexOutOfBoundsException
                    //cb.setValue(null);
                    //cb.getSelectionModel().clearSelection();
                    });

        root.getChildren().addAll(cb);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

【问题讨论】:

    标签: javafx combobox selection deselect


    【解决方案1】:

    您遇到了JavaFX ComboBox change value causes IndexOutOfBoundsException 问题,这导致了IndexOutOfBoundsException。这些有点痛苦。

    无论如何,您的尝试存在一些逻辑问题:清除所选值将导致编辑器更新其文本,因此即使这样有效,用户也无法输入。因此,您要检查更改的值是否不是输入的值。这似乎解决了这两个问题:

        cb.getEditor().textProperty()
                .addListener((obs, oldValue, newValue) -> {
                    if (cb.getValue() != null && ! cb.getValue().toString().equals(newValue)) {
                        cb.getSelectionModel().clearSelection();
                    }
                });
    

    您可能需要更改toString() 调用,具体取决于您使用的确切转换器。在这种情况下,它会起作用。

    【讨论】:

    • 如果我首先从弹出窗口中选择一个选项,然后尝试将数字添加到它在文本字段中。
    • 以下方法似乎可以解决此问题:if ((cb.getValue() != null &amp;&amp; newValue.trim().length() != 0) &amp;&amp; ! cb.getValue().toString().equals(newValue)) { cb.setValue(Integer.parseInt(newValue)); } 当您执行setValue(..) 时,选择设置为该值。这种方法还增加了弹出式替代项的令人愉悦的效果,该替代项与正在选择的文本字段中写入的内容相匹配。
    • 我的解决方案中的第二个布尔表达式是不必要的:if 语句中的布尔表达式参数应如您所建议的那样:您的解决方案的 if 语句中的代码仍然不正确,我的解决方案在上面的评论中(使用您的布尔参数)仍然是迄今为止最好的解决方案。
    猜你喜欢
    • 2023-04-09
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多