对同一个fxml文件使用两个控制器类



到目前为止,我一直在根元素中从fxml文件设置控制器,如下所示

fx:controller = "control.MainController" 

我有一个带有两个选项卡的窗口,每个选项卡都充满了按钮、表格和其他元素。。。为了保持我的项目有序且易于阅读/维护,我想将FirstTabControllerSecondTabController中的控制器代码分开。怎么做?

我可以使用两个不同的文件作为同一fxml文件的控制器类吗?

查看JavaFX TabPane-每个选项卡一个控制器-应该使用fx:include标记。

Main.java(假设所有文件都在sample包中(

package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
public void start(Stage stage) {
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("sample.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(root, 300, 275);
stage.setTitle("FXML Welcome");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}

sample.fxml

<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.Tab?>
<TabPane xmlns:fx="http://javafx.com/fxml">
<Tab text="Tab 1">
<content>
<fx:include source="tab1.fxml"/>
</content>
</Tab>
<Tab text="Tab 2">
<content>
<fx:include source="tab2.fxml"/>
</content>
</Tab>
</TabPane>

表1.fxml

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Label?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.TabOneController">
<Label text="Tab 1"/>
</StackPane>

表2.fxml

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Label?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.TabTwoController">
<Label text="Tab 2"/>
</StackPane>

添加了fx:include标记的FXML文件是单独的文件,可以具有单独的控制器。

最新更新