JavaFX:组合框双向排除

时间:2018-11-16 20:39:57

标签: java javafx combobox

我目前正在尝试在两个组合框之间实现某种“双向排除”行为,但是当用户在两个组合框中都选择一个值时,失败。

基本思想是,如果您在组合框A中选择了一项,则该项目将不再在组合框B中可供选择,反之亦然。

我当前的代码如下(为简单起见,省略了外部类):

@Override
public void initialize(URL location, ResourceBundle resources)
{
    final var sourceList = baseList.filtered(new ExclusionPredicate(null));
    final var targetList = baseList.filtered(new ExclusionPredicate(null));

    initChangeListener(sourceSelection, targetList);
    initChangeListener(targetSelection, sourceList);

    sourceSelection.setItems(sourceList);
    targetSelection.setItems(targetList);
}

private void initChangeListener(ComboBox<Item> comboBox, FilteredList<Item> targetList)
{
    comboBox.valueProperty().addListener(((observable, oldValue, newValue) -> {
        if(newValue != null)
        {
            targetList.setPredicate(((ExclusionPredicate) targetList.getPredicate()).updateExclusion(newValue));
        }
    }));
}

private class ExclusionPredicate implements Predicate<Item>
{
    private final Item excluded;

    private ExclusionPredicate(Mailbox excluded)
    {
        this.excluded = excluded;
    }

    @Override
    public boolean test(Item item)
    {
        if(item == null)
        {
            return true;
        }

        return item.equals(excluded);
    }

    private ExclusionPredicate updateExclusion(Item excluded)
    {
        return new ExclusionPredicate(excluded);
    }
}

当只有一个组合框包含一个值时,一切都很好-您将无法再在组合框2中看到所选的值。 但是,一旦在组合框2中选择了一个值,两者组合框就会失去其值。

我做错什么了吗,还是无法在JavaFX中实现这种行为?尝试在此处/ Google中搜索,只能找到有关相关组合框的答案,而不能找到双向链接的组合框。

0 个答案:

没有答案