【问题标题】:Using two controller classes for the same fxml file对同一个 fxml 文件使用两个控制器类
【发布时间】:2017-08-28 09:37:06
【问题描述】:

到目前为止,我一直在根元素中像这样从 fxml 文件中设置控制器:

fx:controller = "control.MainController" 

我有一个带有 2 个选项卡的窗口,每个选项卡都充满了按钮、表格和其他元素...为了使我的项目井井有条并易于阅读/维护,我想将FirstTabControllerSecondTabController 中的控制器代码。怎么做?

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

【问题讨论】:

标签: java model-view-controller javafx


【解决方案1】:

查看JavaFX TabPane - One controller for each tab - 你应该使用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>

tab1.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>

tab2.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 文件是可以具有单独控制器的单独文件。

【讨论】:

  • 你好,这个解决方案不起作用,在第16行的主类抛出异常
猜你喜欢
  • 2013-05-28
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 2017-02-05
  • 2015-06-03
相关资源
最近更新 更多