除了数字2和3之外,Tab2和Tab3在各方面都是相同的,但只有一个功能正常。具体来说,将主控制器注入每个选项卡时
package controller.tab;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import controller.MainController;
public class Tab2Controller {
private MainController main;
@FXML public Label lbl2;
@FXML private TextField txt2;
@FXML private Button btn2Save;
@FXML private Button btn2Load;
@FXML private void btn2SaveClicked(ActionEvent event) {
System.out.println("Btn 2 save clicked");
lbl2.setText(txt2.getText());
}
@FXML private void btn2LoadClicked(ActionEvent event) {
System.out.println("Btn 2 load clicked");
lbl2.setText(main.loadLblTextFromTab1());
}
public void init(MainController mainController) {
main = mainController;
System.out.println("IS 2 ON?");
}
这是Tab2的fxml文件。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="206.0" prefWidth="226.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.tab.Tab2Controller">
<children>
<Label fx:id="lbl2" alignment="CENTER" layoutX="37.0" layoutY="46.0" prefHeight="17.0" prefWidth="152.0" text="Default Tab3 text" />
<TextField fx:id="txt2" layoutX="26.0" layoutY="78.0" prefHeight="25.0" prefWidth="174.0" />
<Button fx:id="btn2Save" layoutX="21.0" layoutY="113.0" mnemonicParsing="false" onAction="#btn2SaveClicked" prefHeight="58.0" prefWidth="81.0" text="Save text" />
<Button fx:id="btn2Load" layoutX="105.0" layoutY="113.0" mnemonicParsing="false" onAction="#btn2LoadClicked" prefHeight="58.0" prefWidth="101.0" text="Load from Tab1" />
</children>
</AnchorPane>
init中的print只能在其中一个选项卡中使用。控制台上没有错误显示。它不是fx:ids的混合。
这是调用init的主控制器。
package controller;
import javafx.fxml.FXML;
import controller.tab.Tab1Controller;
import controller.tab.Tab3Controller;
import controller.tab.Tab4Controller;
import controller.tab.Tab5Controller;
public class MainController {
@FXML Tab1Controller tab1Controller;
@FXML Tab3Controller tab3Controller;
@FXML Tab4Controller tab4Controller;
@FXML Tab5Controller tab5Controller;
@FXML public void initialize() {
System.out.println("Application started");
tab1Controller.init(this);
System.out.println("Tab 1 Initialized");
tab3Controller.init(this);
System.out.println("Tab 3 Initialized");
tab4Controller.init(this);
System.out.println("Tab 4 Initialized");
tab5Controller.init(this);
System.out.println("Tab 5 Initialized");
}
public String loadLblTextFromTab1() {
return tab1Controller.lbl1.getText();
}
public void setTab3LabelText(String text) {
tab3Controller.lbl3.setText(text);
}
public void updateLogger(String text) {
tab4Controller.txtArea4.appendText(text + "\n");
}
}