Metody fabryczne
Jeżeli klasa zawiera metodę fabryczną – możemy z niej skorzystać. Używamy atrybutu fx:factory=""
Plik listing09_object_from_fabrics_method.fxml
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.layout.VBox?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.ListView?> <?import java.lang.String?> <?import javafx.collections.FXCollections?> <VBox xmlns:fx="http://javafx.com/fxml"> <Label fx:id="lab1" text="Wybierz najładniejsze imię." /> <ListView> <items> <FXCollections fx:factory="observableArrayList"> <String fx:value="Urszula" /> <String fx:value="Ula" /> <String fx:value="Ulka" /> <String fx:value="Ulessa" /> <String fx:value="Uleńka" /> </FXCollections> </items> </ListView> </VBox>
Powyżej w FXML używamy fabryki FXCollection.observableArrayList()
.
Klasa Listing09_object_from_fabrics_method.java
package codes; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.net.URL; public class Listing09_object_from_fabrics_method extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { URL fxmlUrl = this.getClass().getClassLoader() .getResource("resources/listing09_object_from_fabrics_method.fxml"); VBox root = fxmlUrl != null ? FXMLLoader.load(fxmlUrl) : new VBox(); Scene scene = new Scene(root, 150, 150); stage.setScene(scene); stage.show(); } catch (Exception e) { e.printStackTrace(); } } }
Po uruchomieniu klasy zobaczymy:
