This discussion is archived
3 Replies Latest reply: Apr 2, 2013 11:18 AM by Alexander K RSS

FXML - How to preselect an item in ChoiceBox

913122 Newbie
Currently Being Moderated
What is the FXML equivalent for this (cb is a ChoiceBox):
cb.getSelectionModel().select(1);

I tried something like this:
<ChoiceBox SelectionModel.select="1">
....
</ChoiceBox>

and

<ChoiceBox>
<SelectionModel select="1"/>
....
</ChoiceBox>

but those didn't work
  • 1. Re: FXML - How to preselect an item in ChoiceBox
    885691 Pro
    Currently Being Moderated
    I don't believe there is any way to do that at present. Ideally, I think you'd want to be able to do something like this:
    <ChoiceBox selectedIndex="1">
    ....
    </ChoiceBox>
    However, ListView doesn't currently provide a "selectedIndex" property. Feel free to submit a feature request if you think this would be valuable.

    G
  • 2. Re: FXML - How to preselect an item in ChoiceBox
    913122 Newbie
    Currently Being Moderated
    I added a request here: http://javafx-jira.kenai.com/browse/RT-19198
  • 3. Re: FXML - How to preselect an item in ChoiceBox
    Alexander K Newbie
    Currently Being Moderated
    You can achieve this result using FXML scripting capabilities:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import java.lang.*?>
    <?import java.util.*?>
    <?import javafx.collections.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.paint.*?>
    
    <?language javascript?>
    <AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
      <children>
        <Pane layoutX="81.0" layoutY="39.0" prefHeight="200.0" prefWidth="200.0" />
        <ChoiceBox layoutX="326.0" layoutY="108.0" fx:id="choiceBox">
          <items>
            <FXCollections fx:factory="observableArrayList">
              <String fx:value="Item 1" />
              <String fx:value="Item 2" />
              <String fx:value="Item 3" />
            </FXCollections>
          </items>
        </ChoiceBox>
      </children>
      <fx:script>
         choiceBox.getSelectionModel().select(1);
      </fx:script>
    </AnchorPane>
    Edited by: Alexander K on Apr 2, 2013 11:17 AM

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points