Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

java - Access fields from another Controller in JavaFX

I'm writing small application using JavaFX but I stuck with one problem.

I have fxml files:

MainPane.fxml
Stream.fxml
Play.fxml

and each of them has its own controller:

MainPaneController.java
StreamController.java
PlayController.java

Where in MainPane is:

<GridPane fx:controller="model.MainController" fx:id="mainGrid"
    xmlns:fx="http://javafx.com/fxml" alignment="CENTER" gridLinesVisible="true">

    <children>
        <fx:include source="Stream.fxml"/>
    </children>

    <children>
        <fx:include source="Play.fxml"/>
    </children>
</GridPane>

Play.fxml has this field:

<TextField fx:id="searchField" text="Search" onAction="#search"/>

now when action (enter button) if fired I want to access and change a label in Stream.fxml as follows:

public class PlayController implements Initializable {

    @FXML
    private TextField searchField;

    @FXML
    protected void search() {
        System.out.println("Search");
        String text = searchField.getText();
        //how to access Label in StreamController
    }
}

I would like to avoid binding like

MainPaneController <-> StreamController
MainController <-> PlayController

and access fields like:

mainController.getStreamController.changeLabel(text)

because I hope there is some better way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Expose properties in the "nested" controllers StreamController and PlayController. Those controllers can bind the properties to the UI components they define as needed.

Then inject the nested controllers into MainController as described in the Nested Controllers section of the Introduction to FXML.

Update: Here's a more similar example, where the interacting controllers are both included in a common FXML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...