JavaFX ChoiceBox 添加具有类型安全性的分隔符

标签 javafx javafx-2 javafx-8

我希望在选择框中添加一个分隔符并仍然保留类型安全性。

在我见过的所有示例中,他们只是执行以下操作:

ChoiceBox<Object> cb =  new ChoiceBox<>();
cb.getItems().addAll("one", "two", new Separator(), "fadfadfasd", "afdafdsfas");

有没有人想出一个能够添加分隔符并仍然保持类型安全的解决方案?

我希望如果我想添加分隔符,我应该能够执行以下操作:
ChoiceBox<T> cb = new ChoiceBox<T>();
cb.getSeparators().add(1, new Separator()); // 1 is the index of where the separator should be

我不应该仅仅为了添加分隔符而牺牲类型安全。

最佳答案

如前所述,仅在添加到项目(脏,脏)时才支持分隔符。为了按照问题中预期的方式支持他们,我们需要:

  • 将分隔符列表的概念添加到选择框
  • 让它的皮肤知道该列表

  • 虽然前者没什么大不了,但后者需要完全重写(主要是 c&p)它的皮肤,因为一切都被紧紧地隐藏在隐私中。如果无论如何都发生了重写,那么只需多写几行:-)

    只是为了好玩,我正在尝试 ChoiceBoxX这解决了其选择处理中的一些讨厌的错误,所以忍不住尝试。

    首先,添加对 ChoiceBoxx 本身的支持:
    /**
     * Adds a separator index to the list. The separator is inserted 
     * after the item with the same index. Client code
     * must keep this list in sync with the data.
     * 
     * @param separator
     */
    public final void addSeparator(int separator) {
        if (separatorsList.getValue() == null) {
            separatorsList.setValue(FXCollections.observableArrayList());
        }
        separatorsList.getValue().add(separator);
    };
    

    然后是 ChoiceBoxXSkin 的一些变化
  • 必须听分隔符列表
  • 必须期待 index-of-menuItem != index-of-choiceItem
  • menuItem 必须保持其 index-of-choiceItem

  • 在最简单的情况下,监听器重新构建弹出窗口,menuItem 将 dataIndex 存储在其属性中,并且需要通过其 dataIndex 访问弹出窗口的所有代码都委托(delegate)给一个方法,该方法循环遍历 menuItems 直到找到适合的方法:
    protected RadioMenuItem getMenuItemFor(int dataIndex) {
        if (dataIndex < 0) return null;
        int loopIndex = dataIndex;
        while (loopIndex < popup.getItems().size()) {
            MenuItem item = popup.getItems().get(loopIndex);
    
            ObservableMap<Object, Object> properties = item.getProperties();
            Object object = properties.get("data-index");
            if ((object instanceof Integer) && dataIndex == (Integer) object) {
                return item instanceof RadioMenuItem ? (RadioMenuItem)item : null;
            }
            loopIndex++;
        }
        return null;
    }
    

    关于JavaFX ChoiceBox 添加具有类型安全性的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25914924/

    相关文章:

    javafx - 在 JavaFX 中设置标签和文本字段对齐方式

    java - 如何将 JPanel 嵌入到 JavaFX Pane 中?

    JavaFX ListView 键盘导航

    java - 退出位于 JavaFX 线程外的 JFrame 内的 WebView

    listview - JavaFX : How to focus and select to the next cell with a ListView when scrolling?

    带有自定义对象的 javafx CheckListView 以显示特定属性

    tableview - 请解释如何使用 CheckBoxTableCell

    java - setStroke() 和 setFill() 产生不同的像素颜色

    使用自定义语言的 Javafx 国际化

    java - FXML 资源未加载