Versions Compared

Key

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

...

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 me!" onAction="#handleUpcaseAction"/>
</HBox>

FXML-fil for eksemplet. XML-elementer (tags) svarer stort sett til GUI-elementer, hvor tag-navnet svarer til GUI-klassen.

Code Block
languagejavafx
titleExample2.java
linenumberstrue
package fxcontroller;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
 
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;

	@FXML
    public void handleUpcaseAction(ActionEvent event) {
        textField.setText(textField.getText().toUpperCase());
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

Kode for innlasting av FXML-fil. Koden this.getClass().getResourceAsStream("Example2.fxml") brukes for å lese inn en fil som ligger i samme mappe/pakke som klassen.

...

Code Block
languagejavafx
titleExample3.java
package fxcontroller;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
 
public class Example3 extends Application {
    @Override
    public void start(Stage primaryStage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setController(new Example3Controller());
        Parent root = (Parent) fxmlLoader.load(this.getClass().getResourceAsStream("Example3.fxml"));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}
Code Block
languagejavafx
titleExample3Controller.java
package fxcontroller;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
 
public class Example3Controller {
    @FXML
    private TextField textField;

    @FXML
	public void handleUpcaseAction() {
        textField.setText(textField.getText().toUpperCase());
    }
}

...