Problems copying the content of a HBox from FXML - javafx

in my project, I need to copy the content of an specific HBox from some FXML files acording to the menu clicked, and put it in the HBox related to the content of the main page.
Bellow you can see the hierarchy of the project, and this aproach's goal is to have a global page, changing only the content of this HBox. The HBox in the main and in the other pages has the ID "conteudo".
I was able to copy and paste the content, but it can only happen once. After caling clear() or removeAll() once, it does not work anymore. There is no error also, and I checked and "conteudo" is still there after the remove/clear of it's childrens, any idea why it happens only once?
Note 1: Using ((HBox) fxmlAldeia.lookup("#conteudo")).getChildren() I get acess to the content inside "conteudo".
Note 2: getCenter does not help, because I get only a part of the center.
Note 3: I can not build the content of "conteudo" using java. I do that using Scenebuilder to speedUp, thats why I need to load it from the FXML.
Hierarchy:
Código
package simulador;
public class Aldeia extends Application {
private static Scene sceneAldeia;
protected static BorderPane fxmlAldeia;
protected static BorderPane fxmlEdfPrincipal;
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TW Fake");
fxmlAldeia = FXMLLoader.load(getClass().getResource("Aldeia.fxml"));
fxmlEdfPrincipal = FXMLLoader.load(getClass().getResource("EdfPrincipal.fxml"));
sceneAldeia = new Scene(fxmlAldeia);
primaryStage.setScene(sceneAldeia);
primaryStage.show();
}
public static void changeScreen(String src) throws IOException {
// limpa conteúdo
((HBox) fxmlAldeia.lookup("#conteudo")).getChildren().clear();
switch (src) {
case "aldeia":
((HBox) fxmlAldeia.lookup("#conteudo")).getChildren()
.addAll(((HBox) fxmlAldeia.lookup("#conteudo")).getChildren());
break;
case "edfPrincipal":
((HBox) fxmlAldeia.lookup("#conteudo")).getChildren()
.addAll(((HBox) fxmlEdfPrincipal.lookup("#conteudo")).getChildren());
break;
}
}
public static void main(String[] args) {
launch(args);
}
}

Related

JAVAFX: Get User input using dialog before starting main application window

I have a client application, and I want to get the server address, port, and some other info from the user in order to initialize the controller of the main stage.
Currently my code look like this
public class MemoryGameClient extends Application {
#Override
public void start(Stage mainStage) throws Exception {
FXMLLoader fxml = new FXMLLoader(getClass().getResource("MemoryGameClient.fxml"));
MemoryGameClientController controller = fxml.getController()
Parent root = loader.load();
controller.connect(SERVER_ADDRESS, PORT, GAME_BOARD_SIZE);
Scene scene = new Scene(root);
mainStage.setScene(scene);
mainStage.show()
}
public static void main(String[] args) {
launch(args);
}
}
It works fine using the hardcoded values, but I want to be able to open a DialogPane or something like that to get those values from user before initializing the scene and running the main application logic.
Can I set an empty Scene that launch a dialog and after that quitting and starting the main stage? Can I do that from the controller before mainStage.show()?
(I need the user input not only for connecting the server but also to determine the size of the GridPane in root)

Is it possible to launch a JavaFX application through another JavaFX application?

Can I know why there is an error when I say.
Stage s = new Stage();
new CaeserCipherFX().start(s);
This is my code below. I need to launch another JavaFX Application from this one. Please help. Thank you.
public class Main extends Application
{
String args[];
#Override
public void start(Stage stage) throws Exception
{
// creating types of encryptions (Button)
Button caeserCipher = new Button("1. Caeser Cipher");
Button runningKeyCipher = new Button("2. Running Key Cipher");
Button trithemiusCipher = new Button("3. Trithemius Cipher");
Button vignereCipher = new Button("4. Vignere Cipher");
//setting styles
caeserCipher.setTextFill(Color.BLUE);
runningKeyCipher.setTextFill(Color.BLUE);
trithemiusCipher.setTextFill(Color.BLUE);
vignereCipher.setTextFill(Color.BLUE);
/*need to add more!*/
//setting action listeners
String arr [] = {"CaeserCipher","RunningKeyCipher","TrithemiusCipher","VignereCipher"};
caeserCipher.setOnAction((ActionEvent event)->{
//open caeser cipher
Stage s = new Stage();
new CaeserCipherFX().start(s);
});
runningKeyCipher.setOnAction((ActionEvent event)->{
//open running key cipher
stage.hide();
});
trithemiusCipher.setOnAction((ActionEvent event)->{
//open trithemius cipher
stage.hide();
});
vignereCipher.setOnAction((ActionEvent event)->{
//open vignere cipher
stage.hide();
});
// creating flowpane(FlowPane)
FlowPane menu = new FlowPane();
menu.setHgap(25);
menu.setVgap(25);
menu.setMargin(caeserCipher, new Insets(20, 0, 20, 20));
//list for Flowpane(ObservableList)
ObservableList list = menu.getChildren();
//adding list to flowpane
list.addAll(caeserCipher,runningKeyCipher,trithemiusCipher,vignereCipher);
//scene for stage
Scene scene = new Scene(menu);
stage.setTitle("Main Menu");
stage.setScene(scene);
// stage.initStyle(StageStyle.UTILITY);
stage.setHeight(100);
stage.setWidth(600);
stage.setResizable(false);
// Show the Stage (window)
stage.show();
}
}
And I want to launch the code below:
public class CaeserCipherFX extends Application
{
#Override
public void start(Stage stage) throws Exception
{//some other code
//some other code
}
}
There is a ubiquitous JavaFX main application thread which takes a while to get used to.
Think of it like the front-end thread. Theoretically, you should use that thread to handle UI updates and complex cpu tasks such as looking up something in a BD or figuring out the 100000th decimal of PI should be done in a background thread. If you don't do this, the UI will become unresponsive until the DB data is returned, or that decimal is found.
public class TestClass extends Application {
public static void main(String[] args) {
System.out.println("here");
Application.launch(TestClass.class, args);
System.out.println("this is called once application launch is terminated.");
}
#Override
public void init() throws Exception {
super.init(); //To change body of generated methods, choose Tools | Templates.
System.out.println("message from init");
}
#Override
public void start(Stage primaryStage) throws Exception { // this is abstract.
System.out.println("message from start");
Platform.exit(); // if you remove this line, the application won't exit.
}
}
Since JavaFX comes with some prerequisites, you need to start you rapplication using a front-end. You can work around this, but technically,
public void start(Stage primaryStage)
is what , for all intensive purposes, starts your program.
From here, you can use the primaryStage to control most of your application. It's a good idea to put a .onCloseRequest() on it in which you call Platform.exit();
If you want to have multiple windows in your application, you could use something like
public class TestClass extends Application {
public static void main(String[] args) {
System.out.println("here");
Application.launch(TestClass.class, args);
System.out.println("this is called once application launch is terminated.");
}
#Override
public void init() throws Exception {
super.init(); //To change body of generated methods, choose Tools | Templates.
System.out.println("message from init");
}
#Override
public void start(Stage primaryStage) throws Exception { // this is abstract.
primaryStage.setScene(new Scene(new TextArea("this is the first stage (window)")));
primaryStage.setTitle("stage 1");
primaryStage.show();
primaryStage.setOnCloseRequest((event) -> {
Platform.exit();
});
Stage secondaryStage = new Stage();
secondaryStage.setTitle("stage 2");
TextArea ta2 = new TextArea("this is a different stage.");
Scene scene = new Scene(ta2);
secondaryStage.setScene(scene);
secondaryStage.show();
primaryStage.setX(200);
secondaryStage.setX(200 + primaryStage.getWidth() + 50);
}
}
This is what I assume you want to do. Basically create a new window whenever you press a button. You can create stages like this.
The reason for which you can't do it your way is because you are attempting to start another javafx thread by invoking new CaeserCipherFX which is an application object, not a Stage.
new CaeserCipherFX().start(s); // this can only be called once.
IF you absolutely want to have 2 distinct applications (note: not application windows), then you need to have 2 distinct processes.
Lastly, the primaryStage parameter used in either examples is in the beginning basically a placeholder (as in it's constructed, but there's nothing really in it... like a new String()). You can use different stage objects as your "primary" UI.
Lastly, if depending on the stuff you want to decrypt, you may need to use background threads if you want to keep the UI responsiveness. For this you will need to check out the concurrency part of the javafx tutorial.
Is it possible to launch a JavaFX application through another JavaFX application? Not really.
Alternatively, you can use java.lang.ProcessBuilder
This class essentially sends command lines to your operating system shell.
You can use it to run something like "java -jar XXX\YYY\CaeserCipherFX.jar" whenever you click a button. (you'll have to build a CaeserCypherFX project into a jar file)
This will create a new JVM. This means no memory state sharing. You can handle this through IPC.

How do I switch between layouts in Javax? [duplicate]

I have 2 fxml files:
Layout (header, menubars and content)
Anchorpane (it's supposed to be placed inside the content from the other fxml file)
I would like to know how can I load the second file inside the content space from the "Master" scene. And is that a good thing to do working in javaFX or is it better to load a new scene?
I'm trying to do something like this, but it doesn't work:
#FXML
private AnchorPane content;
#FXML
private void handleButtonAction(ActionEvent event) {
content = (AnchorPane) FXMLLoader.load("vista2.fxml");
}
Thanks for the help.
Why your code does not work
The loader creates a new AnchorPane, but you never add the new pane to a parent in the scene graph.
Quick Fix
Instead of:
content = (AnchorPane) FXMLLoader.load("vista2.fxml");
Write:
content.getChildren().setAll(FXMLLoader.load("vista2.fxml"));
Replacing the content children with your new vista. The content itself remains in the scene graph, so when you set it's children, you are also attaching them to the scene graph at the same time.
You might need to play around with layout (e.g. work with auto resizing layouts like StackPanes rather than AnchorPanes) to get the exact behaviour you want.
Rather than just adopting the quick fix, I would advise reviewing the simple framework linked below as that might provide you with a more general purpose mechanism to get the behaviour you want.
Reference FXML Navigation Framework
I created a small framework for swapping fxml controlled content panes in and out of a portion of the main scene.
The mechanism of the framework is the same as suggested in kithril's answer.
A main pane for the outer fxml acts as a holder for child panes.
The main controller for the outer fxml supplies a public method that can be used to swap the child panes.
A convenience navigator class is statically initialized with the main controller for the outer layout.
The navigator provides a public static method to load a new child pane into the main container (by invoking a method on the main controller).
Child panes are generated in the navigator by their respective fxml loaders.
Why a Framework
The framework seems like overkill for answering your question, and perhaps it is. However, I have found that the two most asked topic related to FXML are:
Navigation between panes generated by FXML (this question).
How to pass data between FXML controllers.
So I felt that a small demo framework was warranted for this case.
Sample Framework Output
The first screen shows the application layout displaying the first vista. The contents are a header which is defined in the main application layout and an aliceblue colored interchangable child content pane.
In the next screen, the user has navigated to the second vista, which retains the constant header from the main layout and replaces the original child pane with a new coral colored child content pane. The new child has been loaded from a new fxml file.
Looking for Something More Substantial?
A lightweight framework which is more extensive and better supported than the sample framework from this question is afterburner.fx.
Looking for Something Even Simpler?
Just swap out the scene root: Changing Scenes in JavaFX.
Other Options?
Animated Transitions and others: Switch between panes in JavaFX
Im not sure about how effective this is, but seems to be just fine and what's more, much simpler to methods above.
https://www.youtube.com/watch?v=LDVztNtJWOo
As far as I understood what is happening here is this(its really similiar to what is happening in Start() method in application class) :
private void buttonGoToWindow3Action(ActionEvent event) throws IOException{
Parent window3; //we need to load the layout that we want to swap
window3 = (StackPane)FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLWindow3"));
Scene newScene; //then we create a new scene with our new layout
newScene = new Scene(window3);
Stage mainWindow; //Here is the magic. We get the reference to main Stage.
mainWindow = (Stage) ((Node)event.getSource()).getScene().getWindow();
mainWindow.setScene(newScene); //here we simply set the new scene
}
However Im not a java expert and quite new to programing so it would be good if someone experienced would evaluate it.
EDIT:
Ive found even simpler method;
Go to MainApplication class and make static Stage parentWindow.
public static Stage parentWindow;
#Override
public void start(Stage stage) throws Exception {
parentWindow = stage;
Parent root = FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLMainScene.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Now you get acces to your main Stage so anywhere in a program you can do something like that to change the scene:
Parent window1;
window1 = FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLWindow1.fxml"));
//Scene newSceneWindow1 = new Scene(window1);
Stage mainStage;
//mainStage = (Stage) ((Node)event.getSource()).getScene().getWindow();
mainStage = MainApplication.parentWindow;
mainStage.getScene().setRoot(newSceneWindow1); //we dont need to change whole sceene, only set new root.
Others may have a better solution, but my solution has been to have a simple container like VBox in the outer fxml, then load the new content and add it as a child of the container. If you're only loading one or two forms, this might be the way go to go. However, for a more complete framework, I found this blog post helpful: https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1 She has source code for her framework which includes fancy transitions. Although it's meant to manage top level scenes, I found it easy to adapt for managing inner content regions too.
My example of the mask.
Using:
Main.getNavigation().load(View2.URL_FXML).Show();
Main.getNavigation().GoBack();
In this case, I recommend you to use custom component instead. First create a custom component for your content:
class Content2 extends AnchorPane {
Content() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("vista2.fxml");
loader.setRoot(this);
loader.setController(this);
loader.load();
}
}
Replace the AnchorPane markup in the root of your vista2.fxml file with fx:root:
<fx:root type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml">
...
</fx:root>
Then, you can do this simply by using custom event binding and arrow function. Add event handler property to your Content class:
private final ObjectProperty<EventHandler<ActionEvent>> propertyOnPreviousButtonClick = new SimpleObjectProperty<EventHandler<ActionEvent>>();
#FXML
private void onPreviousButtonClick(ActionEvent event) {
propertyOnPreviousButtonClick.get().handle(event)
}
public void setOnPreviousButtonClick(EventHandler<ActionEvent> handler) {
propertyOnPreviousButtonClick.set(handler);
}
Finally, bind your custom event handler in your java code or fxml:
#FXML
onNextButtonClick() {
Content2 content2 = new Content2();
content2.setOnPreviousButtonClick((event) -> {
Content1 content1 = new Content1();
layout.getChildren().clear();
layout.getChildren().add(content1);
});
layout.getChildren().clear();
layout.getChildren().add(content2);
}
If you don't want to add content dynamically, just setVisible() to true or false
Got stuck up in this too
Tried out most of the answers, wasn't what I wanted so I just used the ideals given to do this:
public class Main extends Application {
public static Stage homeStage;
#Override
public void start(Stage primaryStage) throws Exception{
homeStage = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("mainView.fxml"));
root.getStylesheets().add(getClass().getResource("stylesheet/custom.css").toExternalForm());
homeStage.setTitle("Classification of Living Organisms");
homeStage.setScene(new Scene(root, 600, 500));
homeStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
this is my main class. Main.java with the landing window/page mainView.fxml.
Used a little of #Tomasz idea, although confused me a lil before I did this in my mainController.java class:
public void gotoSubMenu(Event event) {
Parent window1;
try {
window1 = FXMLLoader.load(getClass().getResource("src/displayView.fxml"));
Stage window1Stage;
Scene window1Scene = new Scene(window1, 600, 500);
window1Stage = Main.homeStage;
window1Stage.setScene(window1Scene);
} catch (IOException e) {
e.printStackTrace();
}
}
created a new Parent window called 'window1' that loaded the second fxml file called 'displayView.fxml' in the src directory.
created an object of the main view stage and set the scene to the newly created scene whose root is window1.
Hope this helps the ones coming into #JavaFX now.
If you're looking for a way to make the button call the new fxml file, this worked for me.
#FXML
private void mainBClicked(ActionEvent event) throws IOException {
Stage stage;
Parent root;
stage=(Stage) ((Button)(event.getSource())).getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Keeping the same scene container but changing the view inside the scene container...
Say the scene container you want to pass a new view and controller into is a GridPane layout named sceneContainer.
Establish a FXMLLoader object of the new view.
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Notifications.fxml"));
Create a matching container and loading the contents of the new view into it.
GridPane yourNewView = fxmlLoader.load();
set the new view to the sceneContainer. (setAll clears all children first)
sceneContainer.getChildren().setAll(yourNewView);
Get the controller object for the new view and call your method that starts the class logic
Notifications notifications = fxmlLoader.getController();
notifications.passUserName(userName);
A full example would look like this :
#FXML
public void setNotificationsViewToScene() {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Notifications.fxml"));
GridPane yourNewView = fxmlLoader.load();
sceneContainer.getChildren().setAll(yourNewView);
Notifications notifications = fxmlLoader.getController();
notifications.passUserName(userName);
} catch (IOException e) {
e.printStackTrace();
}
}
Wow, >8 years old with lots of complicated answers and no mention of the >10 year old solution.
There is a dedicated fx:include element for nesting FXML files. It's not in the SceneBuilder library, so you need to write it manually. SceneBuilder can load and display nested FXML just fine though.
<AnchorPane fx:id="content">
<children>
<fx:include fx:id="nestedVista" source="vista2.fxml" />
</children>
</AnchorPane>
You can reference the nested Pane and controller using the fx:id and fx:id+"Controller"
#FXML
Pane nestedVista;
#FXML
VistaController nestedVistaController;
Documentation link: https://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html#nested_controllers

JavaFX: get controller object from node [duplicate]

I have 2 fxml files:
Layout (header, menubars and content)
Anchorpane (it's supposed to be placed inside the content from the other fxml file)
I would like to know how can I load the second file inside the content space from the "Master" scene. And is that a good thing to do working in javaFX or is it better to load a new scene?
I'm trying to do something like this, but it doesn't work:
#FXML
private AnchorPane content;
#FXML
private void handleButtonAction(ActionEvent event) {
content = (AnchorPane) FXMLLoader.load("vista2.fxml");
}
Thanks for the help.
Why your code does not work
The loader creates a new AnchorPane, but you never add the new pane to a parent in the scene graph.
Quick Fix
Instead of:
content = (AnchorPane) FXMLLoader.load("vista2.fxml");
Write:
content.getChildren().setAll(FXMLLoader.load("vista2.fxml"));
Replacing the content children with your new vista. The content itself remains in the scene graph, so when you set it's children, you are also attaching them to the scene graph at the same time.
You might need to play around with layout (e.g. work with auto resizing layouts like StackPanes rather than AnchorPanes) to get the exact behaviour you want.
Rather than just adopting the quick fix, I would advise reviewing the simple framework linked below as that might provide you with a more general purpose mechanism to get the behaviour you want.
Reference FXML Navigation Framework
I created a small framework for swapping fxml controlled content panes in and out of a portion of the main scene.
The mechanism of the framework is the same as suggested in kithril's answer.
A main pane for the outer fxml acts as a holder for child panes.
The main controller for the outer fxml supplies a public method that can be used to swap the child panes.
A convenience navigator class is statically initialized with the main controller for the outer layout.
The navigator provides a public static method to load a new child pane into the main container (by invoking a method on the main controller).
Child panes are generated in the navigator by their respective fxml loaders.
Why a Framework
The framework seems like overkill for answering your question, and perhaps it is. However, I have found that the two most asked topic related to FXML are:
Navigation between panes generated by FXML (this question).
How to pass data between FXML controllers.
So I felt that a small demo framework was warranted for this case.
Sample Framework Output
The first screen shows the application layout displaying the first vista. The contents are a header which is defined in the main application layout and an aliceblue colored interchangable child content pane.
In the next screen, the user has navigated to the second vista, which retains the constant header from the main layout and replaces the original child pane with a new coral colored child content pane. The new child has been loaded from a new fxml file.
Looking for Something More Substantial?
A lightweight framework which is more extensive and better supported than the sample framework from this question is afterburner.fx.
Looking for Something Even Simpler?
Just swap out the scene root: Changing Scenes in JavaFX.
Other Options?
Animated Transitions and others: Switch between panes in JavaFX
Im not sure about how effective this is, but seems to be just fine and what's more, much simpler to methods above.
https://www.youtube.com/watch?v=LDVztNtJWOo
As far as I understood what is happening here is this(its really similiar to what is happening in Start() method in application class) :
private void buttonGoToWindow3Action(ActionEvent event) throws IOException{
Parent window3; //we need to load the layout that we want to swap
window3 = (StackPane)FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLWindow3"));
Scene newScene; //then we create a new scene with our new layout
newScene = new Scene(window3);
Stage mainWindow; //Here is the magic. We get the reference to main Stage.
mainWindow = (Stage) ((Node)event.getSource()).getScene().getWindow();
mainWindow.setScene(newScene); //here we simply set the new scene
}
However Im not a java expert and quite new to programing so it would be good if someone experienced would evaluate it.
EDIT:
Ive found even simpler method;
Go to MainApplication class and make static Stage parentWindow.
public static Stage parentWindow;
#Override
public void start(Stage stage) throws Exception {
parentWindow = stage;
Parent root = FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLMainScene.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Now you get acces to your main Stage so anywhere in a program you can do something like that to change the scene:
Parent window1;
window1 = FXMLLoader.load(getClass().getResource("/ScenePackage/FXMLWindow1.fxml"));
//Scene newSceneWindow1 = new Scene(window1);
Stage mainStage;
//mainStage = (Stage) ((Node)event.getSource()).getScene().getWindow();
mainStage = MainApplication.parentWindow;
mainStage.getScene().setRoot(newSceneWindow1); //we dont need to change whole sceene, only set new root.
Others may have a better solution, but my solution has been to have a simple container like VBox in the outer fxml, then load the new content and add it as a child of the container. If you're only loading one or two forms, this might be the way go to go. However, for a more complete framework, I found this blog post helpful: https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1 She has source code for her framework which includes fancy transitions. Although it's meant to manage top level scenes, I found it easy to adapt for managing inner content regions too.
My example of the mask.
Using:
Main.getNavigation().load(View2.URL_FXML).Show();
Main.getNavigation().GoBack();
In this case, I recommend you to use custom component instead. First create a custom component for your content:
class Content2 extends AnchorPane {
Content() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("vista2.fxml");
loader.setRoot(this);
loader.setController(this);
loader.load();
}
}
Replace the AnchorPane markup in the root of your vista2.fxml file with fx:root:
<fx:root type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml">
...
</fx:root>
Then, you can do this simply by using custom event binding and arrow function. Add event handler property to your Content class:
private final ObjectProperty<EventHandler<ActionEvent>> propertyOnPreviousButtonClick = new SimpleObjectProperty<EventHandler<ActionEvent>>();
#FXML
private void onPreviousButtonClick(ActionEvent event) {
propertyOnPreviousButtonClick.get().handle(event)
}
public void setOnPreviousButtonClick(EventHandler<ActionEvent> handler) {
propertyOnPreviousButtonClick.set(handler);
}
Finally, bind your custom event handler in your java code or fxml:
#FXML
onNextButtonClick() {
Content2 content2 = new Content2();
content2.setOnPreviousButtonClick((event) -> {
Content1 content1 = new Content1();
layout.getChildren().clear();
layout.getChildren().add(content1);
});
layout.getChildren().clear();
layout.getChildren().add(content2);
}
If you don't want to add content dynamically, just setVisible() to true or false
Got stuck up in this too
Tried out most of the answers, wasn't what I wanted so I just used the ideals given to do this:
public class Main extends Application {
public static Stage homeStage;
#Override
public void start(Stage primaryStage) throws Exception{
homeStage = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("mainView.fxml"));
root.getStylesheets().add(getClass().getResource("stylesheet/custom.css").toExternalForm());
homeStage.setTitle("Classification of Living Organisms");
homeStage.setScene(new Scene(root, 600, 500));
homeStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
this is my main class. Main.java with the landing window/page mainView.fxml.
Used a little of #Tomasz idea, although confused me a lil before I did this in my mainController.java class:
public void gotoSubMenu(Event event) {
Parent window1;
try {
window1 = FXMLLoader.load(getClass().getResource("src/displayView.fxml"));
Stage window1Stage;
Scene window1Scene = new Scene(window1, 600, 500);
window1Stage = Main.homeStage;
window1Stage.setScene(window1Scene);
} catch (IOException e) {
e.printStackTrace();
}
}
created a new Parent window called 'window1' that loaded the second fxml file called 'displayView.fxml' in the src directory.
created an object of the main view stage and set the scene to the newly created scene whose root is window1.
Hope this helps the ones coming into #JavaFX now.
If you're looking for a way to make the button call the new fxml file, this worked for me.
#FXML
private void mainBClicked(ActionEvent event) throws IOException {
Stage stage;
Parent root;
stage=(Stage) ((Button)(event.getSource())).getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Keeping the same scene container but changing the view inside the scene container...
Say the scene container you want to pass a new view and controller into is a GridPane layout named sceneContainer.
Establish a FXMLLoader object of the new view.
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Notifications.fxml"));
Create a matching container and loading the contents of the new view into it.
GridPane yourNewView = fxmlLoader.load();
set the new view to the sceneContainer. (setAll clears all children first)
sceneContainer.getChildren().setAll(yourNewView);
Get the controller object for the new view and call your method that starts the class logic
Notifications notifications = fxmlLoader.getController();
notifications.passUserName(userName);
A full example would look like this :
#FXML
public void setNotificationsViewToScene() {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Notifications.fxml"));
GridPane yourNewView = fxmlLoader.load();
sceneContainer.getChildren().setAll(yourNewView);
Notifications notifications = fxmlLoader.getController();
notifications.passUserName(userName);
} catch (IOException e) {
e.printStackTrace();
}
}
Wow, >8 years old with lots of complicated answers and no mention of the >10 year old solution.
There is a dedicated fx:include element for nesting FXML files. It's not in the SceneBuilder library, so you need to write it manually. SceneBuilder can load and display nested FXML just fine though.
<AnchorPane fx:id="content">
<children>
<fx:include fx:id="nestedVista" source="vista2.fxml" />
</children>
</AnchorPane>
You can reference the nested Pane and controller using the fx:id and fx:id+"Controller"
#FXML
Pane nestedVista;
#FXML
VistaController nestedVistaController;
Documentation link: https://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html#nested_controllers

How to navigate through scenes?

I have created some scenes using sceneBuilder and now i need to link those scenes.for example when the user click the "next" button the next scene is displayed.
In android it is possible to go from one activity(window) to another easily(using Intent and startActivity Method).
Is there anything like that in javafx.
If it isn't .what is the best way to navigate through scenes.
You navigate by replacing the children of your topmost container. In the simplest case, it is the primary stage. So:
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
...
primaryStage.setRoot(view1);
...
}
public void navigateToView2() {
primaryStage.setRoot(view1);
}
You may want to have a common template; in this case your topmost container will be the container of the template.

Resources