i'm using scene builder build javafx gui, , want combobox happen "on showing." looks simple enough, crashes when try implement it. created simple version having nothing combobox, , still crashes.
here main.java module:
package application; import javafx.application.application; import javafx.fxml.fxmlloader; import javafx.stage.stage; import javafx.scene.scene; import javafx.scene.layout.borderpane; public class main extends application { @override public void start(stage primarystage) { try { // borderpane root = new borderpane(); borderpane root = (borderpane) fxmlloader.load(main.class.getresource("comboscreen.fxml")); scene scene = new scene(root,400,400); scene.getstylesheets().add(getclass().getresource("application.css").toexternalform()); primarystage.setscene(scene); primarystage.show(); } catch(exception e) { e.printstacktrace(); } } public static void main(string[] args) { launch(args); } }
here fxml:
<?xml version="1.0" encoding="utf-8"?> <?import javafx.scene.control.combobox?> <?import javafx.scene.layout.borderpane?> <?import javafx.scene.layout.vbox?> <borderpane xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.controller"> <center> <vbox alignment="center" prefheight="400.0" prefwidth="400.0" borderpane.alignment="center"> <children> <combobox fx:id="combotestbox" onaction="#combodo" onshowing="#showaction" prefwidth="150.0" prompttext="testbox" /> </children> </vbox> </center> </borderpane>
and here controller:
package application; import javafx.collections.fxcollections; import javafx.collections.observablelist; import javafx.event.actionevent; import javafx.fxml.fxml; import javafx.scene.control.combobox; public class controller { @fxml public combobox<string> combotestbox; @fxml void combodo(actionevent event) { system.out.println(" option chosen"); } observablelist<string> options = fxcollections.observablearraylist( "option 1", "option 2", "option 3" ); @fxml void showaction(actionevent event) { system.out.println(" testaction"); } public void initialize() { combotestbox.setitems(options); } }
it looks simple enough, crashes every time. if remove "onshowing" action, works fine. advice appreciated, pretty new @ this.
assuming "crashing" mean gives runtime exception (for future reference, please include stack trace, has lots of information diagnose problem, in question):
the onshowing
handler eventhandler<event>
, not eventhandler<actionevent>
, need:
@fxml void showaction(event event) { system.out.println(" testaction"); }
note if you're not using event
parameter, can omit it, , fxmlloader
still able map correct handler method:
@fxml void showaction() { system.out.println(" testaction"); }
however, if include parameter, must of correct type.
as aside, should use proper naming conventions, i.e.
@fxml void showaction(event event) { system.out.println(" testaction"); }
with corresponding change fxml file.