1. 程式人生 > 其它 >JFoenix中文教程:4、JFXComboBox下拉框元件

JFoenix中文教程:4、JFXComboBox下拉框元件

技術標籤:JFoenix中文教程javafxjava

JFoenix提供的下拉元件為JFXComboBox,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);
            }
        });
    }
}