Creating a JavaFX Scene from Button click; Close the created Scene - java

I am learning JavaFX, and creating a scene that will be created and displayed to get user input. I created a VBox that holds different textfields and a button that I want to use to close the scene that was created and then store that information to use elsewhere. I can't seem to figure out how to add functionality to the button that will close the scene.
I've tried adding a EventHandler that will do it, but I can't seem to get the program to work.
part of Controller
public void drawNewClass(ActionEvent actionEvent) throws IOException {
ClassInstance classInstance = new ClassInstance();
TextField classDescription = new TextField("Enter Description");
TextField className = new TextField("Enter Class Name");
Button close = new Button("Submit");
close.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
}
});
TextField attributes = new TextField("Enter Variables (privacy type name, format)");
VBox secondaryLayout = new VBox();
secondaryLayout.getChildren().addAll(classDescription, className, attributes, close);
Scene secondScene = new Scene(secondaryLayout, 230, 100);
// New window (Stage)
Stage newWindow = new Stage();
newWindow.setTitle("Add Class");
newWindow.setScene(secondScene);
// Set position of second window, related to primary window.
newWindow.setX(canvas.getLayoutX() + 200);
newWindow.setY(canvas.getLayoutY() + 100);
newWindow.showAndWait();
.FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.layout.StackPane?>
<BorderPane xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.diagrambuilder.csc260w2022project2.diagramBuilderController"
prefHeight="500.0" prefWidth="500.0"
fx:id="root">
<top>
<HBox>
<Button text="Close" fx:id="closeButton" onAction="#closeApplication"/>
<Button text="New" onAction="#newCanvas"/>
<Button text="Save" onAction="#saveCanvas"/>
<Button text="Save As" onAction="#saveAsCanvas"/>
<Button text="Load" onAction="#loadCanvas"/>
<Button text="Export as Image" onAction="#exportCanvas"/>
</HBox>
</top>
<left>
<VBox>
<Button text="Draw New Class" fx:id="newClass" onAction="#drawNewClass"/>
<Button text="Add New Relationship" onAction="#drawNewRelationship"/>
</VBox>
</left>
<center>
<StackPane fx:id="stackPane" style="-fx-border-color: #000; -fx-border-width: 1px"
maxWidth="500" maxHeight="500">
<Canvas fx:id="canvas" width="${stackPane.width}" height="${stackPane.height}"/>
</StackPane>
</center>
</BorderPane>
Image of GUI

Related

Javafx doesn't display a nested component

To continue this post, I implemented part of the solution that was suggested.
I have my main panel and I want to drew on it a component which is a different class (steerwheel).
My main controller :
public class WindowController {
#FXML SteerWheel steerwheel;
... other componenets..
}
My new component :
public SteeringWheel() {
myLabel = new Label();
innerCircle = new Circle();
backgroundCircle = new Circle();
System.out.println("steerwheel created.");
}
.. other methods..
My mainwindow.fxml file :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<?import view.SteerWheel?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/9.0.1" fx:controller="view.WindowController">
<center>
<SteerWheel fx:id="steerwheel" />
</center>
</BorderPane>
and my steerwheel.fxml file :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.shape.Circle?>
<?import javafx.scene.text.Font?>
<AnchorPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="view.SteerWheel"
prefHeight="400.0" prefWidth="600.0">
<Label fx:id="mylabel" prefHeight="30.0" prefWidth="102.0" text="mytest" translateY="30" translateX="90">
<StackPane >
<Circle fx:id="innerCircle" fill="darkgray" radius="170" />
<Circle fx:id="backgroundCircle " fill="black" radius="80" />
</StackPane>
</AnchorPane>
My main code that loads the fxml files (in a different file from all mentioned) :
public class Main extends Application {
public static Stage primaryStage;
#Override
public void start(Stage primary_stage) {
this.primaryStage=primary_stage;
FXMLLoader fxl=new FXMLLoader();
try {
BorderPane root = fxl.load(getClass().getResource("mainwindow.fxml").openStream());
WindowController wc=fxl.getController();
Scene scene = new Scene(root,700,700);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
I'm seeing the constructor`s output but to the console but the component isn't displayed on the window.
Update
I tried to add a call for the fxml file of the steerwheel in my Window.fxml :
<BorderPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/9.0.1" fx:controller="view.WindowController">
<center>
<VBox maxHeight="-Infinity" prefHeight="450.0" prefWidth="400.0" BorderPane.alignment="TOP_CENTER">
<children>
<fx:include source="steerwheel.fxml" fx:id="steerwheel" />
</children>
</VBox>
</center>
</BorderPane>
Now I'm getting the following error :
Caused by: java.lang.IllegalArgumentException: Can not set view.steerWheel field view.WindowController.steerWheel to javafx.scene.layout.AnchorPane
I found the following post that described the same issue I had :
Passing data from one controller to another in javafx. java.lang.IllegalArgumentException
#fabian also answered there how to solve the issue.
The solution I implemented :
My main fxml file :
<BorderPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/9.0.1" fx:controller="view.WindowController">
<center>
<VBox maxHeight="-Infinity" prefHeight="450.0" prefWidth="400.0" BorderPane.alignment="TOP_CENTER">
<children>
<fx:include fx:id="steerwheel" source="steerwheel.fxml" />
</children>
</VBox>
</center>
</BorderPane>
In the controler of the fxml file I added an AnchorPane object that named after the fx:id and I renamed the steerWheel obj to steerwheelController :
public class WindowController {
#FXML AnchorPane steerwheel;
#FXML steerWheel steerwheelController;
Afterwards, I had to use the setLocation method in my main in order to load the inner fxml file (otherwise I got an error..) :
FXMLLoader fxl=new FXMLLoader();
try {
fxl.setLocation(getClass().getResource("Window.fxml"));
BorderPane root = fxl.load();
WindowController wc=fxl.getController();
Hoping it will help someone :)

FXML Label value is not loaded when new window is opened

When I want to open a new window on a click event I need to load some
a value in a label, but the value is not refreshed.
I have tried load the new window an instantiate the label and set a value to be displayed, but nothing happens.
Bellow is the fxml and the code:
public class PetshopController implements Initializable {
#FXML
public ListView<String> ListaProgramari;
#FXML
public void completeTheAppointment(MouseEvent e) {
try {
String animalName = ListaProgramari.getSelectionModel().getSelectedItem();
DiagnosticController dc = new DiagnosticController();
dc.openDiagnosticWindow(animalName);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public class DiagnosticController implements Initializable{
#FXML
private Label animalName = new Label();
#FXML
public TextField newDiagnostic;
#FXML
public Pane AnimalDetails;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void openDiagnosticWindow(String animalLabel) {
try {
animalName = new Label();
animalName.setText(animalLabel);
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("/controller/Diagnostic.fxml"));
Scene scene = new Scene(root, 600, 400);
scene.getStylesheets().add(getClass().getResource("/controller/application.css").toExternalForm());
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Bellow is the FXML. This contains all the items from the new window which is opened the problem is at the label: "animalName":
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane prefHeight="303.0" prefWidth="452.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.DiagnosticController">
<top>
<MenuBar prefHeight="0.0" prefWidth="480.0" BorderPane.alignment="CENTER" />
</top>
<center>
<SplitPane dividerPositions="0.6445182724252492" orientation="VERTICAL" prefHeight="200.0" prefWidth="160.0" BorderPane.alignment="CENTER">
<items>
<AnchorPane fx:id="AnimalDetails" minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<TextField fx:id="newDiagnostic" layoutX="190.0" layoutY="131.0" />
<Label layoutX="48.0" layoutY="135.0" prefHeight="17.0" prefWidth="120.0" text="Adauga Diagnostic" />
<Label layoutX="42.0" layoutY="75.0" prefHeight="17.0" prefWidth="120.0" text="Numele Animalului:" />
<Label fx:id="animalName" layoutX="189.0" layoutY="75.0" prefHeight="17.0" prefWidth="145.0" text="empty" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="49.0" prefWidth="450.0">
<children>
<Button fx:id="completeConsultation" layoutX="172.0" layoutY="46.0" mnemonicParsing="false" onMouseClicked="#completeConsultation" prefHeight="36.0" prefWidth="79.0" text="Complete" />
</children>
</AnchorPane>
</items>
</SplitPane>
</center>
</BorderPane>
By doing #FXML private Label animalName = new Label(); you construct a new label instead of the one already created by the fxml. In fact you do it twice : this Label is initialized again in openDiagnosticWindow by animalName = new Label();
Just use #FXML public Label animalName;
Another problem is in those lines:
DiagnosticController dc = new DiagnosticController();
dc.openDiagnosticWindow(animalName);
dc is a reference to an instance of DiagnosticController but not the instance used by the fxml.
To get a reference of the controller used by the fxml you need to get it from the loader:
FXMLLoader loader = new FXMLLoader();
BorderPane root = loader.load(getClass().getResource("/controller/Diagnostic.fxml") .openStream());
DiagnosticController dc = (DiagnosticController)loader.getController();
which means loading Diagnostic.fxml should be done by PetshopController and not by DiagnosticController.
For more help please post mcve. Important information is missing (like what is the name of the fxml file posted ? What invokes PetshopController ? and more) which forces us to guess.

JavaFX / FXML UI does not look like it should

I have a UI I have made using Netbeans and Scene builder using Java FX / FXML. I have never had a problem with it before but for this project for some reason in Scene building my UI would look one way, even the windows preview would look identical to it, but when running it in netbeans it would look messed up. In netbeans, all I am doing is loading and calling it. I have no idea on what the issue can be and nothing is helping on Google.
working screen shot on scene builder and editing and netbeans
http://imgur.com/laZYjck
compile and run
http://imgur.com/NOMVBZe
main.java
public class main
{
public static void main(String[] args)
{
View view = new View();
view.launch();
}
}
view.java
public class View extends Application
{
#FXML
private Button login;
#Override
public void start(Stage primaryStage)
{
Parent login_page = null;
try {
login_page = FXMLLoader.load(getClass().getResource("FXMLViewLogin.fxml"));
}
catch (IOException ex)
{
}
primaryStage.setTitle("Welcome!");
primaryStage.setScene(new Scene(login_page));
primaryStage.show();
}
#FXML
private void login(ActionEvent event)
{}
}
FXMLViewLogin.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="520.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.ViewControllerLogin">
<children>
<Button fx:id="button1" defaultButton="true" layoutX="74.0" layoutY="296.0" text="Sign Up" />
<Label layoutX="198.0" layoutY="153.0" text="Password" />
<Label layoutX="187.0" layoutY="35.0" text="User Name" />
<TextField fx:id="password" layoutX="74.0" layoutY="204.0" />
<TextField fx:id="username" layoutX="74.0" layoutY="80.0" />
<Button fx:id="button" layoutX="323.0" layoutY="296.0" onAction="#login" text="Log In" />
</children>
</Pane>

How do i restart an application in JavaFx, built with FXML?

Say I have a window, with a button. And everytime that button is pressed I want the current window to be disposed and a new one to be shown.
In Swing, that was easy, but I can't find the syntax for it in JavaFx?
So in this case, with my example code, how do I do this?
public class Main extends Application {
Parent root;
Scene scene;
#Override
public void start(Stage primaryStage) throws Exception {
root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.setResizable(false);
primaryStage.show();
root.setOnMouseClicked((MouseEvent mouseEvent) -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
Stage stage = new Stage();
stage.setScene(primaryStage.getScene());
stage.show();
primaryStage.close();
}
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Trying to create a new window: http://sv.tinypic.com/r/1jkq4w/8
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<VBox prefHeight="430.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="blackjack.FXMLDocumentController">
<children>
<AnchorPane maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
<children>
<Label fx:id="labelPlayerTotal" layoutX="510.0" layoutY="335.0" prefHeight="15.0" prefWidth="121.0" text="Playertotal:" />
<Label fx:id="labelDealerTotal" layoutX="510.0" layoutY="359.0" prefHeight="15.0" prefWidth="112.0" text="Dealertotal:" />
<TextArea fx:id="dealerArea" layoutY="29.0" prefHeight="159.0" prefWidth="503.0" />
<TextArea fx:id="playerArea" layoutY="244.0" prefHeight="159.0" prefWidth="503.0" />
<Button fx:id="stayButton" layoutX="512.0" layoutY="173.0" mnemonicParsing="false" onAction="#drawCardForDealer" prefHeight="25.0" prefWidth="72.0" text="STAY" />
<Button fx:id="hitButton" layoutX="512.0" layoutY="130.0" mnemonicParsing="false" onAction="#drawCardForPlayer" prefHeight="25.0" prefWidth="72.0" text="HIT" />
<Label fx:id="labelWinner" layoutX="104.0" layoutY="208.0" prefHeight="15.0" prefWidth="296.0" />
<MenuBar fx:id="helpBar">
<menus>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" onAction="#aboutApplication" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
</children>
</VBox>
You can just hide (i.e. dispose) the window by calling hide() or close() on it.
And you can just show a new window with exactly the same code you used before:
primaryStage.close();
Stage stage = new Stage();
root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
scene = new Scene(root);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(false);
stage.show();
But this seems like way too much for what you want to achieve. Why not just replace the root of the existing scene, and use the existing stage?
try {
scene.setRoot(FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")));
} catch (Exception exc) {
exc.printStackTrace();
throw new RuntimeException(exc);
}
Note though that (either way you do this) you have now replaced the root of the scene; the new root does not have the same mouse handler associated with it. If you use the second method, you can just put the handler on the scene (which doesn't change) instead. Or, perhaps better, is that you can define the listener in the FXML and controller:
<VBox prefHeight="430.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="blackjack.FXMLDocumentController"
fx:id="root"
onMouseClicked="reload">
<!-- ... -->
</VBox>
And the controller:
package blackjack ;
public class FXMLDocumentController {
// ...
#FXML
private VBox root ;
// ...
#FXML
private void reload() throws Exception {
// Really, it would be way better here to reset the whole UI to its initial
// state, instead of reloading it from scratch. This should work as a
// quick hack though.
Scene scene = root.getScene();
scene.setRoot(FXMLLoader.load(Main.class.getResource("FXMLDocument.fmxl")));
}
// ...
}

JavaFX 2.0 FXML Child Windows

After much searching I found this question How to create a javafx 2.0 application MDI. What I really wanted to know is if I can create a pop-up window or child window to the main window using JavaFX components and Scene Builder to create the new window.
I ended up with this for a modal pop-up window:
In the Main class I wanted to save the primary stage to a field I can access from my primary controller class. So, I added a static variable Stage to it and this in the Main.Start() method:
primaryController.primaryStage = primaryStage;
This the method that a button in the primaryController uses:
public void OnBtnShowChild(ActionEvent event) {
MessageBoxController msgBox = new MessageBoxController();
try {
msgBox.showMessageBox(primaryStage);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the MessageBoxController class that I created with help from Scene Builder. It has the basic layout of a standard pop-up box that can be used to display an Icon (ImageView), TextBox (for your message text), and two buttons (for YES/NO functionality). I am not sure yet how to have it communicate the results of what button was pressed back to the primaryController.
public class MessageBoxController implements Initializable {
#FXML
// fx:id="btnNo"
private Button btnNo; // Value injected by FXMLLoader
#FXML
// fx:id="btnYes"
private Button btnYes; // Value injected by FXMLLoader
#FXML
// fx:id="imgMessage"
private ImageView imgMessage; // Value injected by FXMLLoader
#FXML
// fx:id="txtMessage"
private TextField txtMessage; // Value injected by FXMLLoader
private Stage myParent;
private Stage messageBoxStage;
public void showMessageBox(Stage parentStage) {
this.myParent = parentStage;
try {
messageBoxStage = new Stage();
AnchorPane page = (AnchorPane) FXMLLoader.load(MessageBoxController.class.getResource("/MessageBox/MessageBoxFXML.fxml"));
Scene scene = new Scene(page);
messageBoxStage.setScene(scene);
messageBoxStage.setTitle("Message Box");
messageBoxStage.initOwner(this.myParent);
messageBoxStage.initModality(Modality.WINDOW_MODAL);
messageBoxStage.show();
} catch (Exception ex) {
System.out.println("Exception foundeth in showMessageBox");
ex.printStackTrace();
}
}
#Override
public void initialize(URL fxmlFileLocation, ResourceBundle arg1) {
txtMessage.setText("Howdy");
}
public void OnBtnYes(ActionEvent event) {
}
public void OnBtnNo(ActionEvent event) {
}
}
And finally, this is the FXML file I created in Scene Builder:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane2" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
prefHeight="172.0" prefWidth="524.0" xmlns:fx="http://javafx.com/fxml" fx:controller="MessageBox.MessageBoxController">
<children>
<VBox prefHeight="172.0" prefWidth="524.0" styleClass="vboxes" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<HBox alignment="CENTER" prefHeight="109.99990000000253" prefWidth="516.0" spacing="30.0">
<children>
<ImageView fx:id="imgMessage" fitHeight="110.0" fitWidth="146.66666666666666" pickOnBounds="true" preserveRatio="true" styleClass="null" />
<TextField fx:id="txtMessage" editable="false" prefHeight="47.0" prefWidth="325.0" />
</children>
<stylesheets>
<URL value="#MyCSS.css" />
</stylesheets>
</HBox>
<HBox alignment="CENTER" prefHeight="58.0" prefWidth="516.0" spacing="30.0">
<children>
<Button fx:id="btnYes" mnemonicParsing="false" onAction="#OnBtnYes" text="Button" />
<Button fx:id="btnNo" mnemonicParsing="false" onAction="#OnBtnNo" text="Button" />
</children>
</HBox>
</children>
<stylesheets>
<URL value="#MyCSS.css" />
</stylesheets>
</VBox>
</children>
<stylesheets>
<URL value="#MyCSS.css" />
</stylesheets>
</AnchorPane>
With this I can create a modal pop-up window, and I also want to create other child windows for displaying data in other ways using different controls. And, most importantly, I can use Scene Builder to create the layout.
What do you think? Is this a good way to do this until they add real support in Java 8 and JavaFX 8?
did you try wit the Group class? you can add diferent elements with fxml and controllers.
Group root= new Group();
AnchorPane frame=FXMLLoader.load(getClass().getResource("frame.fxml"));
AnchorPane content= FXMLLoader.load(getClass().getResource("principal.fxml"));
root.getChildren().add(window);
root.getChildren().add(frame);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();

Categories