你好,我被困在一个点上,以获得对包含ComboBox的父对象的引用$ ComboBoxSelectionModel是否有可能以某种方式访问它?
我想编写单个ChangeListener并为许多ComboBox注册它,然后在ChangeListener对象中更改伪类状态,但我需要对Object进行更改的引用。
new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
if (observable instanceof ReadOnlyObjectProperty)
((ReadOnlyObjectProperty) observable).getBean();
}
};
这将返回ComboBox $ ComboBoxSelectionModel @ 7a1f9092但是如何访问包含此选择模型的ComboBox对象?
由于
答案 0 :(得分:0)
1)使用功能(James_D建议):
comboBox.getSelectionModel().selectedItemProperty().addListener(getListener(comboBox));
ChangeListener<YourType> getListener(ComboBox<YourType> comboBox){
return (o,ov,nv)->{
// Use comboBox here
};
}
2)使用反射:
ChangeListener<YourType> listener = (o,ov,nv)->{
try{
ComboBox<?> comboBox = getCaller(o);
...
} catch (NoSuchFieldException | IllegalAccessException e) {
...
}
}
ComboBox<?> getCaller(ObservableValue<?> observable) throws NoSuchFieldException, IllegalAccessException {
final Object bean = ((ReadOnlyProperty<?>)observable).getBean();
final Class<?> selectionModelClass = bean.getClass();
final Field field = selectionModelClass.getDeclaredField("comboBox");
field.setAccessible(true);
return (ComboBox<?>) field.get(bean);
}
要获取ChoiceBox,请使用:selectionModelClass.getDeclaredField(“ choiceBox”);