Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Det er praktisk at GUI-strukturen automatisk bygges, men det blir samtidig upraktisk å få tak i (referanser) til de interaktive GUI-elementene, så en kan få lagt til lyttere og implementert kontroller-logikk. Dersom en f.eks. skal reagere på trykk på "Click me!"-knappen, så må en lete gjennom children-lista til root-elementet og finne knappen, for så å bruke cast og legge til lytteren. Heldigvis har FXML støtte for nettopp å koble elementer i GUI-strukturen til kontroller-logikk, som vist under:

Image Removed
Code Block
languagejavafx
titleExample2.fxml
linenumberstrue
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.HBox?>

<HBox xmlns:fx="http://javafx.com/fxml">
    <TextField fx:id="textField" text="Type something here!"/>
    <Button text="Click here to change to upper caseme!" onAction="#handleUpcaseAction"/>
</HBox>
Code Block
languagejavafx
titleExample2.java
linenumberstrue
public class Example2 extends Application {
    @Override
    public void start(Stage primaryStage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setController(this);
        Parent root = (Parent) fxmlLoader.load(this.getClass().getResourceAsStream("Example2.fxml"));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    @FXML
    private TextField textField;
    public void handleUpcaseAction(ActionEvent event) {
        textField.setText(textField.getText().toUpperCase());
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

...

Code Block
languagejavafx
titleExample4.fxml
<HBox xmlns:fx="http://javafx.com/fxml"
    fx:controller="javafx.fxmlexamples.Example4Controller">
    <TextField fx:id="textField" text="Type something here!"/>
    <Button text="Click here to change to upper caseme!" onAction="#handleUpcaseAction"/>
</HBox>

 

 

Code Block
languagejavafx
titleExample4.java
public class Example4 extends Application {
    @Override
    public void start(Stage primaryStage) throws IOException {
        Parent root = FXMLLoader.load(this.getClass().getResource("Example3.fxml"));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

...