加载新场景时如何保留工具栏?
到目前为止,这是我的代码:
主类
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
primaryStage.setTitle("Test FXML application");
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Main.fxml
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ToolBar?>
<GridPane fx:controller="main.java.Controller"
xmlns:fx="http://javafx.com/fxml">
<ToolBar prefHeight="40.0" prefWidth="400.0">
<Button text="testButton" onAction="#testButton"/>
</ToolBar>
</GridPane>
Controller.class
我认为问题出在这里。我生成下一个场景的方式有点问题。
public class Controller {
@FXML
private void testButton1() throws IOException {
Parent window1;
try {
window1 = FXMLLoader.load(getClass().getResource("src/testButton1.fxml"));
Stage window1Stage;
Scene window1Scene = new Scene(window1, 400, 400);
window1Stage = Main.main();
window1Stage.setScene(window1Scene);
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
有比 GridPane
更合适的布局来替换部分内容,但基本上你需要为 ToolBar
使用一个父级,它允许你替换额外的子级.在这种情况下,BorderPane
可能是个好主意,但它也可以用 GridPane
来完成;它只是不够优雅。
<BorderPane fx:id="container" fx:controller="main.java.Controller"
xmlns:fx="http://javafx.com/fxml">
<top>
<ToolBar prefHeight="40.0" prefWidth="400.0">
<Button text="testButton" onAction="#testButton"/>
</ToolBar>
</top>
</BorderPane>
@FXML
private BorderPane container;
@FXML
private void testButton1() throws IOException {
try {
container.setCenter(FXMLLoader.load(getClass().getResource("src/testButton1.fxml")));
container.getScene().getWindow().sizeToScene(); // resize scene to fit the full size of the content
} catch (IOException e) {
e.printStackTrace();
}
}
如果您继续使用 GridPane
,请使用 fx:id
注入(inject)它,确保 ToolBar
是您想要的唯一子项keep,它是位于 rowIndex=0, columnIndex=0)
的第一个 child 和唯一的 child ,您也可以手动删除其他 child :
@FXML
private GridPane container;
@FXML
private void testButton1() throws IOException {
ObservableList<Node> children = container.getChildren();
children.remove(1, children.size()); // remove every child after the first
try {
container.add(FXMLLoader.load(getClass().getResource("src/testButton1.fxml")), 0, 1);
container.getScene().getWindow().sizeToScene(); // resize scene to fit the full size of the content
} catch (IOException e) {
e.printStackTrace();
}
}
关于JavaFX - 加载下一个场景时保留工具栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286130/