FXML 如何设置选择框默认值

use*_*186 0 java javafx javafx-2 fxml javafx-8

我试图设置我的选择框的默认选定项目,但是它没有按预期工作......

<ChoiceBox fx:id="d" value="- Select choice -">
    <String fx:value="hellow"/>
</ChoiceBox>
Run Code Online (Sandbox Code Playgroud)

小智 5

这个答案在问题JavaFX & FXML: how do I set the default selected item in a ChoiceBox in FXML?

例如,当您想选择第二个值作为默认值时,您可以在FXML文件中执行以下操作:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="choicebox.defaultselection.FXMLDocumentController">
    <children>
        <ChoiceBox layoutX="16.0" layoutY="52.0" prefWidth="150.0" value="5 minutes">
            <items>
                <FXCollections fx:factory="observableArrayList">
                    <String fx:value="2 minutes" />
                    <String fx:value="5 minutes" />
                    <String fx:value="15 minutes" />
                </FXCollections>
            </items>
        </ChoiceBox>
    </children>
</AnchorPane>
Run Code Online (Sandbox Code Playgroud)


Fer*_*tel 5

您可以.setValue("");用于设置默认值.. 指出valuename应该存在于observablearray("","","")

例子

@fxml
private ChoiceBox choiceId; // this is fxml choicebox Id name given in fxml file

ObservableList<String> options = FXCollections.observableArrayList("valuename1","valuename2");

choiceId.setValue("valuename1"); // this statement shows default value 

choiceId.setItems(options); // this statement adds all values in choiceBox
Run Code Online (Sandbox Code Playgroud)