Button
A Button in JavaFX is a UI control that the user can click to trigger an action.
Think of it like:
- “Submit”
- “Login”
- “Next”
When the user clicks it → something happens.
1️⃣ FXML: Define a Button
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="20" alignment="CENTER" xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.MyController">
<Button text="Click Me" fx:id="myButton" onAction="#handleButtonClick"/>
</VBox>
Explanation:
fx:controller="com.example.MyController"→ links this FXML to your controller class.fx:id="myButton"→ gives the button an ID so you can access it in the controller.onAction="#handleButtonClick"→ calls a method in the controller when the button is clicked.
2️⃣ Controller: Handle the Button
package com.example;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Alert;
public class MyController {
// Link the button from FXML
@FXML
private Button myButton;
// Method called when button is clicked
@FXML
private void handleButtonClick() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Button Clicked");
alert.setHeaderText(null);
alert.setContentText("You clicked the button!");
alert.showAndWait();
}
}
Explanation:
@FXML→ allows JavaFX to inject the button from the FXML into the controller.handleButtonClick()→ this method runs whenever the user clicks the button.- We used an Alert to show a message, but you could do anything here (change text, open a new window, etc.).
3️⃣ Main Class: Load the FXML
package com.example;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("my_layout.fxml"));
Scene scene = new Scene(loader.load(), 300, 200);
stage.setScene(scene);
stage.setTitle("Button Example");
stage.show();
}
public static void main(String[] args) {
launch();
}
}
✅ Summary:
- FXML defines the button and links to the controller.
- Controller handles actions and UI logic.
- Main class loads FXML and shows the stage.