Using FXML to Build the GUI - Java JavaFX

Java examples for JavaFX:FXML

Description

Using FXML to Build the GUI

Demo Code

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import java.io.IOException;
import java.net.URL;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);/*from   ww w. jav a2 s.co m*/
  }

  @Override
  public void start(Stage stage) throws IOException {
    URL fxmlUrl = this.getClass()
      .getClassLoader()
      .getResource("resources/fxml/test.fxml");

    VBox root = FXMLLoader.<VBox>load(fxmlUrl);
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setTitle("Hello FXML");
    stage.show();
  }
}

The Contents of the test.fxml File

<?xml version="1.0" encoding="UTF-8"?>
<?language javascript?>
<?import javafx.scene.Scene?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>

<VBox spacing="10" xmlns:fx="http://javafx.com/fxml">
        <Label fx:id="msgLbl" text="this is a test" prefWidth="150"/>
        <Button fx:id="sayHelloBtn" text="Say Hello" onAction="sayHello()"/>
        <style>
               -fx-padding: 10;
               -fx-border-style: solid inside;
               -fx-border-width: 2;
               -fx-border-insets: 5;
               -fx-border-radius: 5;
               -fx-border-color: blue;
        </style>
        <fx:script>
               function sayHello() {
                       msgLbl.setText("Hello from FXML!");
               }
        </fx:script>
</VBox>

Related Tutorials