I'm working in JavaFX & Scene Builder trying to get a single button to display text in the console (just to see that it's working), but it's not responding. I have no idea as to why it is not firing. My button's id is fx:id="testButton.

public class Main extends Application
{
    @FXML // fx:id=testButton
    final Button testButton = new Button("Test");

    private void actionListeners()
    {

        testButton.setOnAction(new EventHandler<ActionEvent>()
        {

            @Override
            public void handle(ActionEvent event) 
            {       
                System.out.println("Working");
            }

        });
    }

    @Override
    public void start(Stage primaryStage) throws IOException 
    {
        Parent page = FXMLLoader.load(Main.class.getResource("TestFXML.fxml"));
        Scene scene = new Scene(page);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Testing");
        primaryStage.show();

        actionListeners();
    }

    public static void main(String[] args) 
    {
        launch(args);
    }
有帮助吗?

解决方案

@FXML tag means that annotated variable will be populated by FXML engine. So you shouldn't call new Button() for that variable.

Usually there is a separate class for fxml controller, which populates @FXML variables and handlers. See example here: https://blogs.oracle.com/jmxetc/entry/connecting_scenebuilder_edited_fxml_to

In your example you either overrode variable created by FXML or didn't set FXML Controller correctly in the .fxml file. Provide fxml content to check latter case.

其他提示

You can also annotated handlers for button actions directly without having to explicitly call ...setOnAction(...) methods. This is a little easier and removes a lot of boilerplate code that was required in Java AWT/Swing for managing events (such as you have).

The tutorials in Oracle are pretty good at explaining this, but as a simple example, you just need to add the onAction="#handlingMethod" as an attribute to the button and then add a corresponding @FXML public void handlingMethod(ActionEvent evt) {....} to the controller. For example:

FXML

<Button onAction="#doATask" text="Do A Tas" />

Controller

@FXML public void doATask(ActionEvent evt) {....}

As mentioned above you need to make sure that you have the controller set for the FXML (declaring it in the FXML is the easiest for you at this point, although you can set it programatically if you need to). With this method, you don't even necessarily need a reference to the Button object to work with it, which helps keeps the code a a little cleaner.

It really is that simple, which is one reason why I like JavaFX bounds above Swing or AWT development.

Good luck.

  • chooks
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top