Home > Java > javaTutorial > How can I integrate a controller class into my JavaFX application?

How can I integrate a controller class into my JavaFX application?

Linda Hamilton
Release: 2024-11-03 18:50:03
Original
711 people have browsed it

How can I integrate a controller class into my JavaFX application?

How can I use a controller class with my JavaFX application?

JavaFX applications often use a controller class to manage the application's user interface (UI). The controller class is responsible for handling events, updating the UI, and communicating with the application's model.

To create a controller class, you can use the @FXML annotation to bind elements in the UI to fields in the controller class. For example, the following code creates a controller class that handles events for a button and a label:

<code class="java">public class MyController {

    @FXML
    private Button myButton;

    @FXML
    private Label myLabel;

    public void initialize() {
        myButton.setOnAction(event -> myLabel.setText("Hello, world!"));
    }
}</code>
Copy after login

You can then specify the controller class in the FXML file for the application. For example, the following FXML file specifies that the MyController class is the controller for the application:

<code class="xml"><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import javafx.fxml.FXMLLoader?>

<VBox xmlns="http://javafx.com/javafx/8"
      xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="my.package.MyController">

    <children>
        <Button fx:id="myButton" text="Click me!">
        <Label fx:id="myLabel" text="Hello, world!">
    </children>

</VBox></code>
Copy after login

Once you have created a controller class and specified it in the FXML file, you can use the controller class to handle events, update the UI, and communicate with the application's model.

The above is the detailed content of How can I integrate a controller class into my JavaFX application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template