java - How to cause a ComboBox EventHandler to be triggered when programmatically selecting items? -
the combobox control has method called setonaction. method takes in eventhandler called described documentation:
the combobox action, invoked whenever combobox value property changed. may due value property being programmatically changed, when user selects item in popup list or dialog, or, in case of editable comboboxes, may when user provides own input (be via textfield or other input mechanism.
when stage first loads, don't want combobox default empty value, want automatically select first option in combobox (if has one). getselectionmodel().selectfirst() methods change selection of combobox, reason not trigger eventhandler. however, eventhandler button calls exact same methods will cause eventhandler trigger. doing wrong?
here brief test case shows behavior using jdk 8u40:
import javafx.application.*; import javafx.stage.*; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.control.*; public class test extends application { public void start(stage stage) throws exception { hbox pane = new hbox(); combobox<string> combobox = new combobox<>(); combobox.getitems().add("hello"); combobox.getitems().add("world"); combobox.setonaction((e) -> { system.out.println(combobox.getselectionmodel().getselecteditem()); }); button button = new button("select first"); button.setonaction((e) -> { combobox.getselectionmodel().selectfirst(); }); combobox.getselectionmodel().selectfirst(); pane.getchildren().add(combobox); pane.getchildren().add(button); scene scene = new scene(pane); stage.setscene(scene); stage.show(); } }
i don't entirely understand why necessary, in order eventhandler passed setonaction() method trigger combobox control, stage must first shown show() method.
import javafx.application.*; import javafx.stage.*; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.control.*; public class test extends application { public void start(stage stage) throws exception { hbox pane = new hbox(); combobox<string> combobox = new combobox<>(); combobox.getitems().add("hello"); combobox.getitems().add("world"); combobox.setonaction((e) -> { system.out.println(combobox.getselectionmodel().getselecteditem()); }); button button = new button("select first"); button.setonaction((e) -> { combobox.getselectionmodel().selectfirst(); system.out.println("the button did it!"); }); button.fire(); pane.getchildren().add(combobox); pane.getchildren().add(button); scene scene = new scene(pane); stage.setscene(scene); stage.show(); combobox.getselectionmodel().selectfirst(); } }
this doesn't seem entirely true controls. in above example, calling fire() method on button trigger eventhandler before stage shown.
Comments
Post a Comment