Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX & FXML: how do I set the default selected item in a ChoiceBox in FXML?

I have the following FXML:

<ChoiceBox>
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="2 minutes" />
            <String fx:value="5 minutes" />
            <String fx:value="15 minutes" />
        </FXCollections>
    </items>
</ChoiceBox>

But in the GUI it just shows a ChoiceBox with a default of nothing. I would like the first element in the list to be the default, and for a choice of "null" or nothing to be prohibited.

How do I accomplish this?

like image 752
tadasajon Avatar asked Aug 15 '13 01:08

tadasajon


People also ask

What JavaFX is used for?

JavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.

What is replacing JavaFX?

GWT, Vaadin, Qt, JSF, and Electron are the most popular alternatives and competitors to JavaFX.

Why is JavaFX being removed?

Oracle is removing JavaFX from the Java Development Kit (JDK) 11, given an overall desire to pull out noncore modules from the JDK and retire them or stand them up as independent modules. The open source JavaFX 11 provides a client application platform for desktop, mobile, and embedded systems.

What is difference between Java and JavaFX?

JavaFX is an open-source web platform that enables developers to create modern user interfaces for desktop, mobile, and browser applications. Java Swing is a GUI toolkit for Java, originally designed by Sun Microsystems. It is one of the most popular toolkits in the world.


2 Answers

I added the value attribute to the ChoiceBox tag, and that worked.

<ChoiceBox value="2 minutes">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="2 minutes" />
            <String fx:value="5 minutes" />
            <String fx:value="15 minutes" />
        </FXCollections>
    </items>
</ChoiceBox>
like image 91
tadasajon Avatar answered Sep 21 '22 08:09

tadasajon


First, you should import your needed value model, like Crowell answer, you should import like this in your fxml header:

<?import javafx.collections.*?>

Second, if you want's import your own model, import it first and then like this:

<?import com.zzg.mybatis.generator.model.*?>
....

<ChoiceBox layoutX="24.0" layoutY="14.0" prefWidth="150.0">
      <items>
            <FXCollections fx:factory="observableArrayList">
                  <DatabaseDTO name="MySQL" value="1"></DatabaseDTO>
                  <DatabaseDTO name="Oracle" value="2"></DatabaseDTO>
            </FXCollections>
      </items>
</ChoiceBox>
like image 40
astarring Avatar answered Sep 20 '22 08:09

astarring