问题
I want to use JavaFX in my new project and want something like in the screenshot below.
On the left site I need a navigation bar and on the right my content. So, I would use a VBox on the left side and maybe an AnchorPane on the right side (or better a ScrollPane).
And when I click on the Button "Security" it should load my "Security" Scene on the right side. But how can I manage that. Did not find any solution for this.
Thanks a lot
回答1:
This is an exemplary implementation of such navigation. Here the view described in view_1.fxml
is loaded by default:
<BorderPane fx:id="mainBorderPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
<left>
<VBox spacing="5">
<Button text="btn 1" onAction="#handleShowView1"/>
<Button text="btn 2" onAction="#handleShowView2"/>
<Button text="btn 3" onAction="#handleShowView3"/>
</VBox>
</left>
<center>
<fx:include source="view_1.fxml"/>
</center>
</BorderPane>
And this is the controller
public class Controller {
@FXML
private BorderPane mainBorderPane;
@FXML
private void handleShowView1(ActionEvent e) {
loadFXML(getClass().getResource("/sample/view_1.fxml"));
}
@FXML
private void handleShowView2(ActionEvent e) {
loadFXML(getClass().getResource("/sample/view_2.fxml"));
}
@FXML
private void handleShowView3(ActionEvent e) {
loadFXML(getClass().getResource("/sample/view_3.fxml"));
}
private void loadFXML(URL url) {
try {
FXMLLoader loader = new FXMLLoader(url);
mainBorderPane.setCenter(loader.load());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
update
This is a conversion in which the views are listed directly in the FXML file
<BorderPane fx:id="mainBorderPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
<left>
<VBox spacing="5">
<Button text="btn 1" userData="/sample/view_1.fxml" onAction="#handleShowView"/>
<Button text="btn 2" userData="/sample/view_2.fxml" onAction="#handleShowView"/>
<Button text="btn 3" userData="/sample/view_3.fxml" onAction="#handleShowView"/>
</VBox>
</left>
<center>
<fx:include source="view_1.fxml"/>
</center>
</BorderPane>
and controller
public class Controller {
@FXML
private BorderPane mainBorderPane;
@FXML
private void handleShowView(ActionEvent e) {
String view = (String) ((Node)e.getSource()).getUserData();
loadFXML(getClass().getResource(view));
}
private void loadFXML(URL url) {
try {
FXMLLoader loader = new FXMLLoader(url);
mainBorderPane.setCenter(loader.load());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
来源:https://stackoverflow.com/questions/48019690/javafx-navigationbar-and-contentpane