22

When I create a JavaFX 2.0 ChoiceBox instance like this:

final ChoiceBox<String> fontChBox = 
  new ChoiceBox<>(FXCollections.observableArrayList("First", "Second", "Third"));

a choice box is displayed with no selection. I would like to select the first element by default. How to do it in JavaFX 2.0?

jilt3d
  • 3,864
  • 8
  • 34
  • 41

3 Answers3

49

Give a try to this statement:

 fontChBox.getSelectionModel().selectFirst();
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • Actually there is no such a method setSelectedIndex in SingleSelectionModel but there is a selectFirst method which comes to help. – jilt3d Mar 07 '12 at 16:51
  • Please, modify your post so I can select it as accepted answer, thanks! – jilt3d Mar 07 '12 at 16:51
  • It has but it is protected. http://docs.oracle.com/javafx/2.0/api/javafx/scene/control/SingleSelectionModel.html – jilt3d Mar 07 '12 at 17:01
2

Try this,

fontChBox.getSelectionModel().select(0);

if you need to select an element other than the first, pass the index of the element instead of zero.

2

Try following solution

//use this to display first option.
mychoicebox.getSelectionModel().selectFirst();


//to display specific option
mychoicebox.getSelectionModel().selectFirst(index position);
Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41