簡體   English   中英

使用沒有 FXML 的 JavaFX 控制器

[英]Using JavaFX controller without FXML

是否有可能在不使用 FXML 的情況下使用帶有 JavaFX GUI 的控制器。

我注意到 FXML 文件包含一個fx-controller屬性來綁定控制器,但我認為它不是一種簡單的方法來使用它。

關於在不使用 FXML 文件或 JavaFX Scene Builder 的情況下使用 JavaFX 建立 MVC 架構的任何想法?

您的問題對我來說不是特別清楚:您只需創建類並基本上將所有內容與聽眾聯系在一起。 我不知道這是否有幫助,但這里有一個簡單的例子,它只有幾個文本字段和一個顯示它們總和的標簽。 這就是我認為的“經典 MVC”:如果模型發生變化,視圖會觀察模型並更新 UI 元素。 它向 UI 元素注冊處理程序,並在事件發生時委托給控制器:控制器依次處理輸入(如有必要)並更新模型。

型號:

package mvcexample;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.property.SimpleIntegerProperty;

public class AdditionModel {
    private final IntegerProperty x = new SimpleIntegerProperty();
    private final IntegerProperty y = new SimpleIntegerProperty();
    private final ReadOnlyIntegerWrapper sum = new ReadOnlyIntegerWrapper();

    public AdditionModel() {
        sum.bind(x.add(y));
    }

    public final IntegerProperty xProperty() {
        return this.x;
    }

    public final int getX() {
        return this.xProperty().get();
    }

    public final void setX(final int x) {
        this.xProperty().set(x);
    }

    public final IntegerProperty yProperty() {
        return this.y;
    }

    public final int getY() {
        return this.yProperty().get();
    }

    public final void setY(final int y) {
        this.yProperty().set(y);
    }

    public final javafx.beans.property.ReadOnlyIntegerProperty sumProperty() {
        return this.sum.getReadOnlyProperty();
    }

    public final int getSum() {
        return this.sumProperty().get();
    }



}

控制器:

package mvcexample;

public class AdditionController {

    private final AdditionModel model ;

    public AdditionController(AdditionModel model) {
        this.model = model ;
    }

    public void updateX(String x) {
        model.setX(convertStringToInt(x));
    }

    public void updateY(String y) {
        model.setY(convertStringToInt(y));
    }

    private int convertStringToInt(String s) {
        if (s == null || s.isEmpty()) {
            return 0 ;
        }
        if ("-".equals(s)) {
            return 0 ;
        }
        return Integer.parseInt(s);
    }
}

查看:

package mvcexample;

import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

public class AdditionView {
    private GridPane view ;
    private TextField xField;
    private TextField yField;
    private Label sumLabel;

    private AdditionController controller ;
    private AdditionModel model ;

    public AdditionView(AdditionController controller, AdditionModel model) {

        this.controller = controller ;
        this.model = model ;

        createAndConfigurePane();

        createAndLayoutControls();

        updateControllerFromListeners();

        observeModelAndUpdateControls();

    }

    public Parent asParent() {
        return view ;
    }

    private void observeModelAndUpdateControls() {
        model.xProperty().addListener((obs, oldX, newX) -> 
                updateIfNeeded(newX, xField));

        model.yProperty().addListener((obs, oldY, newY) -> 
                updateIfNeeded(newY, yField));

        sumLabel.textProperty().bind(model.sumProperty().asString());
    }

    private void updateIfNeeded(Number value, TextField field) {
        String s = value.toString() ;
        if (! field.getText().equals(s)) {
            field.setText(s);
        }
    }

    private void updateControllerFromListeners() {
        xField.textProperty().addListener((obs, oldText, newText) -> controller.updateX(newText));
        yField.textProperty().addListener((obs, oldText, newText) -> controller.updateY(newText));
    }

    private void createAndLayoutControls() {
        xField = new TextField();
        configTextFieldForInts(xField);

        yField = new TextField();
        configTextFieldForInts(yField);

        sumLabel = new Label();

        view.addRow(0, new Label("X:"), xField);
        view.addRow(1, new Label("Y:"), yField);
        view.addRow(2, new Label("Sum:"), sumLabel);
    }

    private void createAndConfigurePane() {
        view = new GridPane();

        ColumnConstraints leftCol = new ColumnConstraints();
        leftCol.setHalignment(HPos.RIGHT);
        leftCol.setHgrow(Priority.NEVER);

        ColumnConstraints rightCol = new ColumnConstraints();
        rightCol.setHgrow(Priority.SOMETIMES);

        view.getColumnConstraints().addAll(leftCol, rightCol);

        view.setAlignment(Pos.CENTER);
        view.setHgap(5);
        view.setVgap(10);
    }

    private void configTextFieldForInts(TextField field) {
        field.setTextFormatter(new TextFormatter<Integer>((Change c) -> {
            if (c.getControlNewText().matches("-?\\d*")) {
                return c ;
            }
            return null ;
        }));
    }
}

應用類:

package mvcexample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MVCExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        AdditionModel model = new AdditionModel();
        AdditionController controller = new AdditionController(model);
        AdditionView view = new AdditionView(controller, model);

        Scene scene = new Scene(view.asParent(), 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

我廣泛使用 JavaFX,不使用 FXML 或場景構建器。 所以我可以保證它可以做到。

下面是我的 IDE 為獲取 JavaFX 主類而自動生成的代碼。 這將是您的應用程序的根。 然后,您將添加到它以創建您的應用程序。

public class NewFXMain extends Application {

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

對於我們其他人......這是一個非常簡單的示例,展示了如何在不使用任何 FXML 文件的情況下創建 JavaFX 表單。 這個例子可以在已經運行的應用程序中使用,所以我跳過了 Main 類和所有這些......它只是為了展示 JavaFX 的簡單性。

簡而言之,您只需根據 AnchorPane 等容器創建場景,然后創建舞台並將場景分配給舞台……添加控件然后顯示舞台

package javafx;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class SimpleFX {

    private AnchorPane anchorPane;

    private TextArea textArea () {
        TextArea textArea = new TextArea();
        textArea.setLayoutX(20);
        textArea.setLayoutY(20);
        textArea.setMaxWidth(450);
        textArea.setMinHeight(380);
        return textArea;
    }

    private TextField textField () {
        TextField textField = new TextField();
        textField.setLayoutX(20);
        textField.setLayoutY(410);
        textField.setMinWidth(450);
        textField.setMinHeight(25);
        return textField;
    }

    private Button button() {
        Button button = new Button("Button");
        button.setLayoutX(240);
        button.setLayoutY(450);
        return button;
    }


    private void addControls    () {
        anchorPane.getChildren().add(0,textArea());
        anchorPane.getChildren().add(1,textField());
        anchorPane.getChildren().add(2,button());
    }

    public void startForm () {
        anchorPane = new AnchorPane();
        Scene scene = new Scene(anchorPane, 500, 500);
        Stage stage = new Stage();
        stage.setScene(scene);
        addControls();
        stage.show();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM