B4J Code Snippet How to use controllers in Scene Builder

This is not suitable if you cannot program in java.

Any one who has used scene builder would have seen for each control, on the right hand pane, a tab called code. We use the fx:id, so b4j knows which control we are referring to.
In that tab are things like OnAction with a text field below it to enter something.

You can use them directly from your b4j program, by a slight edit to the fxml file, and adding a few lines of java.

1, Edit the fxml file ( I use notepad++)
Add the following to the Anchorpane definition.
B4X:
fx:controller="b4j.example.main$myControl"
so it reads something like (the numbers may vary)
B4X:
<AnchorPane fx:id="scene1" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="b4j.example.main$myControl">
2, In the designer you can use the code tab and assign names to the events.
eg, in the On Action box enter 'buttonClicked'
and save the layout. Don't worry the scene builder is kind and doesn't wipe out the changes in step 1.
3, In your b4j program add a #if java ... #end if section after your subs
4, Add similar code to this to handle the events.
B4X:
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.scene.input.MouseEvent;
import javafx.fxml.FXML;

public static class myControl {

    @FXML private Button button1;
    @FXML
    void handleButtonClick(ActionEvent event) {
        System.out.println("You pressed me!!");
    }
    @FXML
    void handleNoDontDragMe(MouseEvent event) {
        System.out.println("Naughty!!! don't drag me");
    }
}
My layout simply has a button, called button1.

Now when you run the program, the routines in the java will handle the button press and drag.

Using this method, you can add any missing actions to controls that b4j doesn't natively support.

Attached is my sample project.
 

Attachments

  • fxml test.zip
    1.4 KB · Views: 369
Last edited:
Top