How to get an element in JavaFx using id?

I am new to FXML and I am trying to create a handler for all button clicks with switch. However, for this I need to get the elements and id. I tried the following, but for some reason (perhaps because I do it in the controller class, and not basically), I get an exception.

public class ViewController {
public Button exitBtn;

public ViewController() throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("mainWindow.fxml"));
    Scene scene = new Scene(root);

    exitBtn = (Button) scene.lookup("#exitBtn");
}

}

So, how do I get an element (like a button) using its id as a link?

Fxml block for button:

<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />

+4
source share
1 answer

Use a controller class, so you do not need to use a search. FXMLLoaderwill enter the fields into the controller for you. Injection is guaranteed before the method initialize()(if you have one) is called

public class ViewController {

    @FXML
    private Button exitBtn ;

    @FXML
    private Button openBtn ;

    public void initialize() {
        // initialization here, if needed...
    }

    @FXML
    private void handleButtonClick(ActionEvent event) {
        // I really don't recommend using a single handler like this,
        // but it will work
        if (event.getSource() == exitBtn) {
            exitBtn.getScene().getWindow().hide();
        } else if (event.getSource() == openBtn) {
            // do open action...
        }
        // etc...
    }
}

FXML:

<!-- imports etc... -->
<SomePane xmlns="..." fx:controller="my.package.ViewController">
<!-- ... -->
    <Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
    <Button fx:id="openBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Open" HBox.hgrow="NEVER" HBox.margin="$x1" />
</SomePane>

, FXML , (, , Application)

Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);   
// etc...     
+2

Source: https://habr.com/ru/post/1626409/


All Articles