I'm trying to use a Label text from another controller.. Hear is my Code
Design view
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cbc.MainController">
<children>
<BorderPane prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<top>
<AnchorPane prefHeight="78.0" prefWidth="600.0" BorderPane.alignment="CENTER">
<children>
<Label fx:id="lblName" layoutX="506.0" layoutY="32.0" text="Rifat" />
</children>
</AnchorPane>
</top>
<left>
<AnchorPane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<Button fx:id="btnHome" layoutX="49.0" layoutY="39.0" mnemonicParsing="false" onAction="#btnHome" text="Home" />
<Button fx:id="btnOne" layoutX="36.0" layoutY="87.0" mnemonicParsing="false" onAction="#btnOne" text="Seen One" />
<Button fx:id="btnTwo" layoutX="36.0" layoutY="136.0" mnemonicParsing="false" onAction="#btnTwo" text="Seen Two" />
</children>
</AnchorPane>
</left>
<center>
<AnchorPane fx:id="acContent" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
</children>
</AnchorPane>
Then i include another fxml file into fx:id="acContent"
by this code
public class MainController implements Initializable {
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
acContent.getChildren().clear();
acContent.getChildren().add(FXMLLoader.load(getClass().getResource("Home.fxml")));
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
}
on Home.fxml
i insert a label and a button . if i click the button then label text will change as fx:id="lblName"
which is a node from Main.fxml. and of-course Main.fxml and Home.fxml has different Controller.
You can getController of Home.fxml
this way:
FXMLLoader fxmlLoader = new FXMLLoader();
try {
fxmlLoader.load(getClass().getResource("Home.fxml").openStream());
MyControllerClass controller = fxmlLoader.getController();
// Or use this to find your label
Label myLabel = (Label) fxmlLoader.getNamespace().get("lblName");
} catch (IOException e) {
e.printStackTrace();
}
UPDATE:
So here is more code to explain it a little bit better: Lets suppose you have your fxml file, some MainViewController
controller and some ListItemController
and ListItemController has fxml with Label you want to change. Here is what you can do: https://gist.github.com/varren/ac08d1855322c685adcf
fxmlLoader.getNamespace().get("lblName");
will try to find view with id lblName
specified in your xml
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.