我试着为一个复杂的gui构建一个骨架,所以我的想法就是在javafx 2.1中用mvc做样式,所以每个组件都有一个fxml文件,如果需要css,controller和model。我试着找出如何更改子场景(运行时的子fxml)。有谁知道怎么做?我有点坚持这个。可以添加MainViewController吗?场景:用户点击任务栏中的按钮,包含的content1.fxml将替换为content2.fxml
这里是基本代码
MainApp.java
Loads the MainView.fxml
MainView.fxml
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane xmlns:fx="http://javafx.com/fxml">
<center>
<fx:include source="Content1.fxml"/>
</center>
<bottom>
<fx:include source="TaskBar.fxml"/>
</bottom>
</BorderPane>
Content1.fxml
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:id="content1">
<Label text="Hallo Java FX 2.1.1 Content1.fxml"/>
</StackPane>
Content2.fxml
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:id="content2">
<Label text="Hallo Java FX 2.1.1 Content2.fxml"/>
</StackPane>
TaskBar.fxml
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml" spacing="10" alignment="center"
fx:id="taskBar" fx:controller="TaskBarController">
<children>
<Button fx:id="taskBarButton1" onAction="#handleTaskBarButton1Action"/>
<Button fx:id="taskBarButton2" onAction="#handleTaskBarButton2Action"/>
</children>
</HBox>
TaskBarController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
public class TaskBarController implements Initializable {
// Binding with the FXML
@FXML
private Button taskBarButton1;
@FXML
private Button taskBarButton2;
@FXML
private void handleTaskBarButton1Action(ActionEvent event) {
System.out.println("click! taskBarButton1");
}
@FXML
private void handleTaskBarButton2Action(ActionEvent event) {
System.out.println("click! taskBarButton2");
}
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:20)
不要只包含fxml,为此创建业务逻辑层:
<BorderPane xmlns:fx="http://javafx.com/fxml">
<center>
<Pane fx:id="content"/>
</center>
并在按钮点击处理程序中更新它:
@FXML
private void handleTaskBarButton2Action(ActionEvent event) {
System.out.println("click! taskBarButton2");
content.getChildren().clear();
content.getChildren().add(FXMLLoader.load(getClass().getResource("Content2.fxml"));
}
答案 1 :(得分:3)
它可以工作,thx求助,但是我被迫删除了TaskBar.fxml和TaskBarController.java,写了一个带有@FXML句柄的MainViewController和用于按钮的@FXML和带有fx:id =&#34的Pane;内容&#34; ,并将我的习惯按钮放在MainView.fxml
中@FXML
private void handleTaskBarButton2Action(ActionEvent event) throws IOException {
System.out.println("click! taskBarButton2");
content.getChildren().clear();
content.getChildren().add((Node) FXMLLoader.load(getClass().getResource("Content2.fxml")));
}