JavaFX buttons and labels

Main.java



import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Contololler.java



package sample;

import javafx.scene.control.Button;
import javafx.scene.control.Label;

public class Controller {
    public Button btn01;
    public Label lb01;

    public void onButtonClicked() {
        String string;
        string = "Button clicked";

        lb01.setText(string);

    }
}


sample.fxml



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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.GridPane?>

<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <Button fx:id="btn01" mnemonicParsing="false" onAction="#onButtonClicked" text="Button" GridPane.columnIndex="1" GridPane.rowIndex="1" />
   <Label fx:id="lb01" prefHeight="17.0" prefWidth="86.0" text="Label" />

</GridPane>

You don't have to add a button in Main

The label changes when you press the button

btn.png

Recommended Posts

JavaFX buttons and labels
JavaFX and HiDPI
Hello world with Kotlin and JavaFX
Drag and drop files with JavaFX
Scaling and translation with JavaFX Canvas (Revenge)