我希望在选择框中添加一个分隔符并仍然保留类型安全性。
在我见过的所有示例中,他们只是执行以下操作:
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 的一些变化
在最简单的情况下,监听器重新构建弹出窗口,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/