JFoenix提供的下拉组件为JFXComboBox,JFXComboBox样式如下:
对应源码如下:
<JFXComboBox layoutX="50" layoutY="40" fx:id="jfxComboBox" prefWidth="200" promptText="请选择">
<items>
<FXCollections fx:factory="observableArrayList">
<Label>选项一</Label>
<Label>选项二</Label>
<Label>选项三</Label>
<Label>选项四</Label>
<Label>选项五</Label>
</FXCollections>
</items>
</JFXComboBox>
<JFXComboBox layoutX="300" layoutY="40" fx:id="jfxEditableComboBox" prefWidth="200" promptText="请选择/自定义" editable="true" onMouseClicked="#selectItem">
<items>
<FXCollections fx:factory="observableArrayList">
<Label>选项一</Label>
<Label>选项二</Label>
<Label>选项三</Label>
<Label>选项四</Label>
<Label>选项五</Label>
</FXCollections>
</items>
</JFXComboBox>
JFXComboBox中的 editable 用于设置时候开启自定义编辑,在开启自定义编辑后需要自定义监听事件,否则选择结果会出现混乱。
@FXMLController
public class JFoenixViewController {
@FXML
private JFXComboBox<Label> jfxEditableComboBox;
public void selectItem() {
ChangeListener<? super Boolean> comboBoxFocus = (o, oldVal, newVal) -> {
if (!newVal) {
jfxEditableComboBox.validate();
}
};
jfxEditableComboBox.focusedProperty().addListener(comboBoxFocus);
jfxEditableComboBox.getEditor().focusedProperty().addListener(comboBoxFocus);
jfxEditableComboBox.setConverter(new StringConverter<Label>() {
@Override
public String toString(Label object) {
return object == null ? "" : object.getText();
}
@Override
public Label fromString(String string) {
return string == null || string.isEmpty() ? null : new Label(string);
}
});
}
}