Good Morning! I have just started ramping up on Java FX and Java FX FXML. I'm using Scene Builder to build the GUI and Netbeans to code the remaining Java FX program.
The issue I'm facing is in FXML File. The Netbeans editor shows an error on the following code in .fxml file for onAction Event.
Error that I see in fxml file:
Controller is NOT defined on root component.
Exception Text:
Executing sample1.jar using platform C:\Program
Files\Java\jdk1.8.0_121\jre/bin/java Exception in Application start
method java.lang.reflect.InvocationTargetException at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at
com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start
method at
com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745) Caused by:
javafx.fxml.LoadException: No controller specified.
file:/C:/Users/hmitty/Documents/NetBeansProjects/sample1/dist/run1317822864/sample1.jar!/sample1/FXMLDocument.fxml:21
at
javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2597)
at javafx.fxml.FXMLLoader.access$100(FXMLLoader.java:103) at
javafx.fxml.FXMLLoader$Element.getControllerMethodHandle(FXMLLoader.java:557)
at
javafx.fxml.FXMLLoader$Element.processEventHandlerAttributes(FXMLLoader.java:599)
at
javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:770)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2823) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2532) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104) at
javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097) at
sample1.Sample1.start(Sample1.java:22) at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at
com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at
com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method) at
com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more Exception running application sample1.Sample1 Picked up
_JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true Java Result: 1
If I create a sample project using Netbeans, it uses AnchorPane and everything seems to be fine. However if I remove AnchorPane and add any other pane and the Button, the onAction Event doesn't work!
I'm a beginner in this language, hence any help/guidance is highly appreciated!
Note: I did my homework for close to half a day in browsing all available solutions as far as I can on StackOverFlow.
The closest I got is this, so any help will definitely move things for me!
https://bugs.openjdk.java.net/browse/JDK-8091582
All the code is pasted below. Let me know if anything else is required!
FXML Code:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.event.ActionEvent?>
<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.111">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Button mnemonicParsing="false" onAction="#ClickedClickMe" text="Click Me!" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Label fx:id="label" GridPane.columnIndex="1" GridPane.rowIndex="2" />
</children>
</GridPane>
Sample1.java
package sample1;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Sample1 extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocumentController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sample1;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private void ClickedClickMe(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Clicked Try me!!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Set controller in fxml file
<GridPane fx:controller="sample1.FXMLDocumentController" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.111">
Related
I am relatively new to JavaFX, FXML and SceneBuilder in general. I am working on a project for uni where I have to build an application which includes the functionality of displaying different lecture profiles. The different profiles are stored in a database and are all instances of a class called "Lecture". I built a first simple scene for the class with SceneBuilder and also created a controller class. The idea now is that whenever a lecture should be displayed the according object is loaded from the database and used to adjust attributes in the controller class which cause the Scene to change. I simulated this by instantiating a Lecture object in my start() method and passing it to a getter-like method which was supposed to change the text of a first label attribute displaying the name of the lecturer. Unfortunately this causes a NullPointerException. All research couldn't help which is why I am here now. I am grateful for any help!
Picture of the GUI:
GUI
Error message with stacktrace:
> Task :Main.main() FAILED
Juni 23, 2022 12:16:04 AM com.sun.javafx.application.PlatformImpl startup
WARNING: Unsupported JavaFX configuration: classes were loaded from 'unnamed module #1796cf6c'
Unsupported JavaFX configuration: classes were loaded from 'unnamed module #1796cf6c'
Juni 23, 2022 12:16:04 AM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 18 by JavaFX runtime of version 17.0.1
Exception in Application start method
Loading FXML document with JavaFX API of version 18 by JavaFX runtime of version 17.0.1
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.NullPointerException: Cannot invoke "unihub.userapplicationsystem.LectureProfileController.loadLecture(unihub.serversystem.model.Lecture)" because "lectureProfileController" is null
at unihub.userapplicationsystem.GUI.start(GUI.java:25)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
Caused by: java.lang.NullPointerException: Cannot invoke "unihub.userapplicationsystem.LectureProfileController.loadLecture(unihub.serversystem.model.Lecture)" because "lectureProfileController" is null
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Execution failed for task ':Main.main()'.
> Process 'command '/Library/Java/JavaVirtualMachines/jdk-17.0.1.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
JavaFX application class:
package unihub.userapplicationsystem;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import unihub.serversystem.model.Lecture;
import java.net.URL;
public class GUI extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
URL lectureProfileStageUML = ClassLoader.getSystemResource("LectureProfileStage.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(lectureProfileStageUML);
Lecture testLecture = new Lecture(1, "EIST", "Krusche");
LectureProfileController lectureProfileController = fxmlLoader.getController();
lectureProfileController.loadLecture(testLecture);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
Main class:
public class Main {
public static void main(String[] args) {
GUI.main(args);
}
}
FXML controller class:
package unihub.userapplicationsystem;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import unihub.serversystem.model.Lecture;
public class LectureProfileController {
private Lecture lecture;
#FXML
private Label lecturerNameLabel;
public void loadLecture(Lecture lecture) {
lecturerNameLabel.setText("lecturer:\n" + lecture.getLecturer());
}
}
FXML file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.text.Font?>
<ScrollPane prefHeight="500.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="unihub.userapplicationsystem.LectureProfileController">
<content>
<FlowPane prefHeight="500.0" prefWidth="400.0">
<children>
<StackPane prefHeight="100.0" prefWidth="400.0">
<children>
<ImageView fitHeight="100.0" fitWidth="400.0" pickOnBounds="true" preserveRatio="false">
<image>
<Image url="#LectureBanner.jpg" />
</image>
</ImageView>
<Label text="lecture name here" translateX="-85.0" translateY="-20.0" StackPane.alignment="BOTTOM_CENTER">
<font>
<Font name="SansSerif Bold" size="21.0" />
</font>
</Label>
</children>
</StackPane>
<GridPane alignment="BOTTOM_RIGHT" hgap="10.0" nodeOrientation="LEFT_TO_RIGHT" prefHeight="150.0" prefWidth="400.0" vgap="10.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="188.0" minWidth="10.0" prefWidth="167.0" />
<ColumnConstraints hgrow="SOMETIMES" maxWidth="173.0" minWidth="10.0" prefWidth="173.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label text="lecturer:
-lecturer here- " GridPane.halignment="LEFT" fx:id="lecturerNameLabel"/>
<Label text="lecture-ID:
-lecture-ID here-" GridPane.halignment="LEFT" GridPane.rowIndex="1" />
<Label text="teaching language:
-language here-" GridPane.halignment="LEFT" GridPane.rowIndex="2" />
<Label text="weekly hours:
-hours here-" GridPane.columnIndex="1" GridPane.halignment="LEFT" GridPane.rowIndex="1" />
<Label text="number of credits:
-credits here-" GridPane.columnIndex="1" GridPane.halignment="LEFT" />
<Button alignment="CENTER" mnemonicParsing="false" prefHeight="10.0" prefWidth="101.0" text="Enroll" GridPane.columnIndex="1" GridPane.rowIndex="2">
<font>
<Font name="SansSerif Regular" size="11.0" />
</font>
</Button>
</children>
<padding>
<Insets left="25.0" right="25.0" top="20.0" />
</padding>
</GridPane>
</children>
</FlowPane>
</content>
</ScrollPane>
The FXMLLoader.load(URL) method is a static method. So your code compiles to
URL lectureProfileStageUML = ClassLoader.getSystemResource("LectureProfileStage.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = FXMLLoader.load(lectureProfileStageUML);
It's obvious from this equivalent version of the code that the instance you defined, fxmlLoader, has not been used to load an FXML file. Consequently it never initializes its controller, and
LectureProfileController lectureProfileController = fxmlLoader.getController();
returns null, resulting in a null pointer exception when you try to do
lectureProfileController.loadLecture(testLecture);
Instead, you should set the location of fxmlLoader and call the no-argument, instance method fxmlLoader.load():
#Override
public void start(Stage primaryStage) throws Exception {
URL lectureProfileStageUML = ClassLoader.getSystemResource("LectureProfileStage.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(lectureProfileStageUML);
// or just:
// FXMLLoader fxmlLoader = new FXMLLoader(lectureProfileStageUML);
// Note no URL is passed here:
Parent root = fxmlLoader.load();
Lecture testLecture = new Lecture(1, "EIST", "Krusche");
LectureProfileController lectureProfileController = fxmlLoader.getController();
lectureProfileController.loadLecture(testLecture);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
As an aside, the construction of your URL is probably wrong. See How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?
And as a second aside, it never makes sense to call a static method from an instance variable. Most IDEs warn you (or at the very least can be configured to warn you) when you accidentally do this. I recommend configuring your IDE to provide a warning (and not ignoring the warning). It was a poor design decision to allow that as valid syntax (the language designers were copying what happens in C++).
I get
javafx.fxml.LoadException:
When I'm loading and fxml file using following line of code.
AnchorPane anchorPane = (AnchorPane)loader.load()
This is my fxml file excluding import statements.
<AnchorPane prefHeight="537.0" prefWidth="374.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.buddhikajay.controller.NewTransactionDialogController">
<children>
<GridPane hgap="5.0" layoutX="30.0" layoutY="10.0" prefHeight="544.0" prefWidth="314.0" vgap="5.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="142.0" minWidth="10.0" prefWidth="69.0" />
<ColumnConstraints hgrow="SOMETIMES" maxWidth="226.0" minWidth="10.0" prefWidth="225.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints maxHeight="70.0" minHeight="10.0" prefHeight="33.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="105.0" minHeight="10.0" prefHeight="38.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="156.0" minHeight="10.0" prefHeight="51.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="154.0" minHeight="10.0" prefHeight="43.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="160.0" minHeight="10.0" prefHeight="43.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="161.0" minHeight="10.0" prefHeight="63.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="301.0" minHeight="10.0" prefHeight="180.0" vgrow="SOMETIMES" />
<RowConstraints maxHeight="231.0" minHeight="10.0" prefHeight="106.0" vgrow="SOMETIMES" />
</rowConstraints>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
</padding>
<children>
<Label text="ID" />
<Label text="Date" GridPane.rowIndex="1" />
<Label text="Amont" GridPane.rowIndex="2" />
<Label text="Person" GridPane.rowIndex="4" />
<Label text="Type" GridPane.rowIndex="3" />
<Label text="Resolved" GridPane.rowIndex="5" />
<Label />
<Label text="Description" GridPane.rowIndex="6" />
<TextField fx:id="idTextField" GridPane.columnIndex="1" />
<TextField fx:id="dateTextField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="amountTextField" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextArea fx:id="descriptionTextArea" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="6" />
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="50.0" prefWidth="225.0" spacing="20.0" GridPane.columnIndex="1" GridPane.rowIndex="7">
<GridPane.margin>
<Insets />
</GridPane.margin>
<padding>
<Insets bottom="10.0" left="20.0" right="10.0" top="10.0" />
</padding>
<children>
<Button fx:id="okButton" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#okActionFired" prefHeight="25.0" prefWidth="75.0" text="Ok" />
<Button fx:id="cancleButton" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#cancleActionFired" prefHeight="25.0" prefWidth="75.0" text="Cancle" />
</children>
</HBox>
<ComboBox fx:id="typeComboBox" prefWidth="150.0" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<ComboBox fx:id="personComboBox" prefWidth="150.0" GridPane.columnIndex="1" GridPane.rowIndex="4" />
<ComboBox fx:id="resolvedComboBox" prefWidth="150.0" GridPane.columnIndex="1" GridPane.rowIndex="5" />
</children>
</GridPane>
</children>
</AnchorPane>
The compiler complains that there is an error in line number 1. I'm sure that the path of fxml file is correct. What is wrong with my code?
Here is the full error stack
javafx.fxml.LoadException:
/C:/Users/Buddhika/Documents/Programming/IdeaProjects/VirtualCreditDesktop/out/production/VirtualCreditDesktop/com/buddhikajay/view/NewTransactionDialog.fxml:9
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:104)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:928)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:967)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:216)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:740)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2701)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2521)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2435)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2403)
at com.buddhikajay.controller.NewTransactionDialogController.showNewTransactionDialog(NewTransactionDialogController.java:68)
at com.buddhikajay.controller.MainApp.start(MainApp.java:51)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
at com.sun.javafx.application.LauncherImpl$$Lambda$50/1976027283.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/301541210.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/474926796.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/1662429848.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$38/519284171.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.InstantiationException: com.buddhikajay.controller.NewTransactionDialogController
at java.lang.Class.newInstance(Class.java:423)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:923)
... 23 more
Caused by: java.lang.NoSuchMethodException: com.buddhikajay.controller.NewTransactionDialogController.<init>()
at java.lang.Class.getConstructor0(Class.java:3074)
at java.lang.Class.newInstance(Class.java:408)
... 25 more
The problem is described in the stack trace:
Caused by: java.lang.NoSuchMethodException: com.buddhikajay.controller.NewTransactionDialogController.()
which basically says your controller class doesn't have a zero-argument constructor.
By default, the FXMLLoader will create the controller by calling its zero-argument constructor. Remove the constructor that you have defined in the controller class, or remove the parameters that it takes.
If you really need to pass arguments to the controller's constructor, you can either create the controller in Java code and pass it to the FXMLLoader:
NewTransactionDialogController controller = new NewTransactionDialogController(someValue);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(...);
loader.setController(controller);
AnchorPane anchorPane = loader.load();
(Using this code, you must remove the fx:controller attribute from the FXML.)
Or, set a controller factory:
FXMLLoader loader = new FXMLLoader();
loader.setLocation(...);
loader.setControllerFactory(clazz -> {
if (clazz == NewTransactionDialogController.class) {
return new NewTransactionDialogController(someValue);
} else {
// default behavior:
try {
return clazz.newInstance();
} catch (Exception exc) {
throw new RuntimeException(exc);
}
}
});
AnchorPane anchorPane = loader.load();
(In this version, leave the fx:controller attribute in the FXML file.)
I was about to enter a different question as remarked by #James_D for my comment because Until I Read the first line of the FXML on this question, I had thought that I had a different problem.
For my sins, I reduced the challenge to a simple example of a single controller and two FXML files. One worked and the second fail/failed.
The starting point is the Netbeans sample "[Click me!]" sample. The code is pasted below. And, first a solution.
As preamble, let me say that it seems that everyone has been blaming the Java controller for these load errors. I had a bunch of errors like this on a project a couple of years ago. We exhausted "controller" debugging and eventually pressed-forward by re-building the FXML screens with ScendBuilder. I didn't have time to investigate further then.
Last week I perfectly working FXML screen started failing to load because we moved it to a runtime directory (previously it was in the JAR resources area).
KLUNK!
After 3 or 4 days tweaking that and this, I made a comment here on my error:
unknown path: 7
Javafx fxml LoadException: Error resolving onAction='#handleButtonAction', either the event handler is not in the Namespace or there is an error in the script.
On only the "simple.fxml" file, but not the "Scene.fxml" file. The file "simple.fxml" is reduced from the app FXML file that initially gave the problem. There were too many variables on that original file, so chop-chop-chop to match the canned demo.
When you use ONLY this:
xmlns:fx="http://javafx.com/fxml"
FXML load-s from files on disk under in your application folder work just like you want them to (well, like I want, anyway). Looking at the FXML above it is using a more 'fragile' namespace, viz.
Queston's original FXML:
<AnchorPane ...
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1" ... >
By using diff, I slowly morphed "simple.fxml" to be as close as possible to "Scene.fxml", and "simple" just keeps failing to load. Please note; always using the same controller
Loading FXML with other metadata has not worked consistently an FXML file was moved. I don't have an explanation as to how this is so.
The FXML is kept in a directory called "test/resources/fxml/simple.fxml" for example. When I was building with both files in the project JAR, the 'same' FXML in both cases loaded and worked as expected. To me there's something un-said about aspects of the file load precess. Again for me, this is undesirable because the KEY value of a external scene definition would be interchange.
These kind of bear traps in XML mark-up that are (apparently) not picked up by development tools like SceneBuilder or the FXMLLoader() are barriers to progress on live projects that don't have slack to investigate esoteric weirdness like this.
This is witnessed by our previous project experience -- I was easier to re-edit a complex screen with SceneBuilder as a whole than track down load problems like this one. The call to action is: Diagnostics on FXML load -- an FXML Lint would be almost a requirement.
Controller, SimpleController.java:
package ex.view.views;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class SimpleController implements Initializable {
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
The failing FXML started life as one of the Maven archetypes (I think) and that file worked fine until I moved the FXML files to a folder and loaded them from a InputStream.
I have formatted the AnchorPane markup on multiple lines for readability.
simple.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320"
xmlns="http://javafx.com/javafx/8.0.65"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="ex.view.views.SimpleController">
<children>
<Button fx:id="button" layoutX="126" layoutY="90" text="Click Me!" />
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
</children>
</AnchorPane>
The working FXML mark-up is from the Netbeans 8.1 samples.
Scene.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.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320"
xmlns:fx="http://javafx.com/fxml"
fx:controller="ex.view.views.SimpleController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
So i made pretty simple application with Fxml with only label and text field, and two buttons but i get this error..
Exception in Application start method
And here is code
<?xml version="1.0" encoding="UTF-8*?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<GridPane alignment="CENTER" hgap="5.0" vgap="5.0">
<children>
<Text text="Dodavanje Kupca" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2">
<font>
<Font size= "30.0"/>
</font>
</Text>
<Label text="Ime Kupca" GridPane.columnIndex="0" GridPane.rowIndex="2"/>
<Label text="Prezime Kupca" GridPane.columnIndex="0" GridPane.rowIndex="3"/>
<Label text="Adresa Kupca" GridPane.columnIndex="0" GridPane.rowIndex="4"/>
<Label text="Email Kupca" GridPane.columnIndex="0" GridPane.rowIndex="5"/>
<Label text="Telefon Kupca" GridPane.columnIndex="0" GridPane.rowIndex="6"/>
<TextField GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<TextField GridPane.columnIndex="1" GridPane.rowIndex="3"/>
<TextField GridPane.columnIndex="1" GridPane.rowIndex="4"/>
<TextField GridPane.columnIndex="1" GridPane.rowIndex="5"/>
<TextField GridPane.columnIndex="1" GridPane.rowIndex="6"/>
<HBox alignment="TOP_RIGHT" GridPane.columnIndex="1" GridPane.rowIndex="7">
<children>
<Button mnemonicParsing="true" text="Save"/>
<Button mnemonicParsing="true" text="Clear"/>
</children>
</HBox>
</children>
<padding>
<Insets bottom="16.0" left="15.0" right="15.0" top="15.0"/>
</padding>
</GridPane>
And here is the main class:
package main;
import java.net.URL;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class test extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
URL fxmlUrl= getClass().getClassLoader().getResource("view.fxml");
GridPane root= FXMLLoader.<GridPane>load(fxmlUrl);
Scene scena = new Scene(root);
stage.setScene(scena);
stage.show();
}
}
Sorry.
Here is another edit for stack trace.
Stack trace is little too big so again ill type some non sense here
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: javafx.fxml.LoadException:
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2504)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at main.test.start(test.java:20)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
... 1 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,22]
Message: A pseudo attribute name is expected.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.setInputSource(XMLStreamReaderImpl.java:214)
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.<init>(XMLStreamReaderImpl.java:184)
at com.sun.xml.internal.stream.XMLInputFactoryImpl.getXMLStreamReaderImpl(XMLInputFactoryImpl.java:262)
at com.sun.xml.internal.stream.XMLInputFactoryImpl.createXMLStreamReader(XMLInputFactoryImpl.java:134)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2478)
... 17 more
Exception running application main.test
C:\Users\Djordje Zlatic\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I'm new to javafx and i was trying to make a gui from which when a button is clicked, it would go to another window. I tried reading many answers found on Stack Overflow. I even tried making the project again from the beginning...But i keep on getting the same error.
That is Exception is Application start method
java.lang.reflect.InvocationTargetException javafx
My Main
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class SkyTravelsFx extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
stage.initStyle(StageStyle.UNDECORATED);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
LoginController.java
package skytravelsfx;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class LoginController implements Initializable {
#FXML
TextField username;
#FXML
TextField password;
#FXML
Button user;
#FXML
Button admin;
#FXML
Button login;
#FXML
public void btnClicked (ActionEvent actionEvent){
try{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("User.fxml"));
Parent root=(Parent) fxmlLoader.load();
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
((Stage)(((Button)actionEvent.getSource()).getScene().getWindow())).hide();
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Please note that i still haven't written any codes in UserController.java
I just made the ui for User.fxml
Login.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="766.0" prefWidth="1366.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="skytravelsfx.LoginController">
<children>
<ImageView fitHeight="866.0" fitWidth="1397.0" layoutX="10.0" layoutY="11.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../../../SkyTravelFx/src/goodwp.com_25168.jpg" />
</image>
</ImageView>
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
<Label fx:id="label1" layoutX="565.0" layoutY="517.0" minHeight="16" minWidth="69" text="Select User">
<font>
<Font size="18.0" />
</font>
</Label>
<Rectangle arcHeight="5.0" arcWidth="5.0" fill="#095a77" height="140.0" stroke="BLACK" strokeType="INSIDE" strokeWidth="0.0" width="1386.0" />
<Label fx:id="label11" layoutX="56.0" layoutY="33.0" minHeight="16" minWidth="69" text="Sky Travels" textFill="WHITE">
<font>
<Font name="System Italic" size="72.0" />
</font>
</Label>
<Label fx:id="label12" layoutX="432.0" layoutY="91.0" minHeight="16" minWidth="69" text="Making your destination closer..." textFill="WHITE">
<font>
<Font name="System Italic" size="18.0" />
</font>
</Label>
<AnchorPane layoutX="83.0" layoutY="252.0" prefHeight="507.0" prefWidth="383.0">
<children>
<ImageView fitHeight="191.0" fitWidth="234.0" layoutX="96.0" layoutY="6.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../../../SkyTravelFx/src/icon-default-profile.png" />
</image>
</ImageView>
<Button fx:id="login" layoutX="153.0" layoutY="440.0" onAction="#handleButtonAction" style="-fx-background-color: #095a77;" text="Log In" textFill="WHITE">
<font>
<Font size="18.0" />
</font>
</Button>
<Label fx:id="label2" layoutX="152.0" layoutY="308.0" minHeight="16" minWidth="69" text="Password">
<font>
<Font size="18.0" />
</font>
</Label>
<Label fx:id="label2" layoutX="150.0" layoutY="214.0" minHeight="16" minWidth="69" text="Username">
<font>
<Font size="18.0" />
</font>
</Label>
<TextField fx:id="username" layoutX="115.0" layoutY="241.0" />
<TextField fx:id="password" layoutX="115.0" layoutY="335.0" />
</children>
</AnchorPane>
<Button fx:id="admin" layoutX="621.0" layoutY="592.0" mnemonicParsing="false" style="-fx-background-color: #095a77;" text="Log In as Admin" textFill="WHITE">
<font>
<Font size="18.0" />
</font>
</Button>
<Button fx:id="user" layoutX="621.0" layoutY="675.0" mnemonicParsing="false" onAction="#btnClicked" prefHeight="39.0" prefWidth="153.0" style="-fx-background-color: #095a77;" text="Log In as User" textFill="WHITE">
<font>
<Font size="18.0" />
</font>
</Button>
</children>
</AnchorPane>
Here is the run-time error i am getting.
Exception in Application start method
java.lang.reflect.InvocationTargetException at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at
com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start
method at
com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745) Caused by:
javafx.fxml.LoadException: Error resolving
onAction='#handleButtonAction', either the event handler is not in the
Namespace or there is an error in the script.
file:/C:/Users/Dell/Documents/NetBeansProjects/SkyTravelsFx/dist/run1245920268/SkyTravelsFx.jar!/skytravelsfx/Login.fxml:47
at
javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2597)
at javafx.fxml.FXMLLoader.access$100(FXMLLoader.java:103) at
javafx.fxml.FXMLLoader$Element.processEventHandlerAttributes(FXMLLoader.java:610)
at
javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:770)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2823) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2532) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104) at
javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097) at
skytravelsfx.SkyTravelsFx.start(SkyTravelsFx.java:23) at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at
com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at
com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method) at
com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more Exception running application skytravelsfx.SkyTravelsFx
Java Result: 1 Deleting directory
C:\Users\Dell\Documents\NetBeansProjects\SkyTravelsFx\dist\run1245920268
jfxsa-run: BUILD SUCCESSFUL (total time: 4 seconds)
The stack trace tells you the problem:
Error resolving onAction='#handleButtonAction', either the event handler is not in the Namespace or there is an error in the script.
You have
<Button fx:id="login" layoutX="153.0" layoutY="440.0" onAction="#handleButtonAction" ... >
but your controller has no method called handleButtonAction. You probably want
<Button fx:id="login" layoutX="153.0" layoutY="440.0" onAction="#btnClicked" ... >
At 76, I am trying to learn Java and have produced a number of accounting related tutorials that successfully change scenes. Now looking at a structure using menubar and menu items to cope with linking 14 chapters as one of the items on the menubar.
All examples I have seen/watched show a simple println for each MenuItem. I have this working OK, but when I try to copy my FXMLLoader from my previous applications it doesn't like it.
I get this cannot find symbol: symbol: method getScene() location: variable mbarchapter1 of type MenuItem
My code is:
package accountingsnapshots;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;
public class AccountingSnapshotsController implements Initializable {
#FXML
private MenuItem mbarhome;
#FXML
private MenuItem mbarchapter1;
#FXML
private MenuItem mbarchapter2;
#FXML
private MenuItem mbarchapter3;
#FXML
private MenuItem mbarchapter4;
#FXML
private MenuItem mbarcalculator;
#FXML
private MenuItem mbarglossary;
#FXML
private MenuItem mbarhelp;
Stage stage;
#FXML Parent root;
#FXML
private void handleButtonAction(ActionEvent e) throws IOException {
if(e.getSource()==mbarhome){
System.out.println("this is Home");
}
else if(e.getSource()==mbarchapter1){
System.out.println("this is chap 1");
//get reference to the button's stage
stage = (Stage) root.getScene().getWindow();
//load up OTHER FXML document
root = FXMLLoader.load(getClass().getResource("AccountingSnapshots_1.fxml"));
//create a new scene with root and set the stage
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
else if(e.getSource()==mbarchapter2){
System.out.println("this is chap 2");
}
else if(e.getSource()==mbarchapter3){
System.out.println("this is chap 3");
}
else if(e.getSource()==mbarchapter4){
System.out.println("this is chap 4");
}
else if(e.getSource()==mbarcalculator){
System.out.println("this is Calculator");
}
else if(e.getSource()==mbarglossary){
System.out.println("this is Glossary");
}
else if(e.getSource()==mbarhelp){
System.out.println("this is Help");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
My FXML file has fx:ids against the menuItems. Shown below:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="accountingsnapshots.AccountingSnapshotsController">
<children>
<MenuBar layoutY="-1.0" prefHeight="30.0" prefWidth="858.0">
<menus>
<Menu fx:id="mbarhome" mnemonicParsing="false" onAction="#handleButtonAction" text="Home">
<items>
<MenuItem mnemonicParsing="false" text="Home" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Chapters">
<items>
<MenuItem fx:id="mbarchapter1" mnemonicParsing="false" onAction="#handleButtonAction" text="Ch.1 - Introduction to final accounts" />
<MenuItem fx:id="mbarchapter2" mnemonicParsing="false" onAction="#handleButtonAction" text="Ch.2 - Double entry bookkeeping" />
<MenuItem fx:id="mbarchapter3" mnemonicParsing="false" onAction="#handleButtonAction" text="Ch.3 - Accounting adjustments" />
<MenuItem fx:id="mbarchapter4" mnemonicParsing="false" onAction="#handleButtonAction" text="Ch.4 - Introduction to final accounts" />
</items>
</Menu>
<Menu fx:id="mbarcalculator" mnemonicParsing="false" onAction="#handleButtonAction" text="Calculator">
<items>
<MenuItem mnemonicParsing="false" text="Calculator" />
</items>
</Menu>
<Menu fx:id="mbarglossary" mnemonicParsing="false" onAction="#handleButtonAction" text="Glossary">
<items>
<MenuItem mnemonicParsing="false" text="Glossary" />
</items>
</Menu>
<Menu fx:id="mbarhelp" mnemonicParsing="false" onAction="#handleButtonAction" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="Help" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
This is the output when running the application:
Created dir: C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\empty
Created dir: C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\generated-sources\ap-source-output
Compiling 2 source files to C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\classes
Copying 5 files to C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\classes
compile:
Created dir: C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0_31\jre\..\lib\ant-javafx.jar
Warning: From JDK7u25 the Codebase manifest attribute should be used to restrict JAR repurposing.
Please set manifest.custom.codebase property to override the current default non-secure value '*'.
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0_31\jre\..\lib\ant-javafx.jar
jfx-deployment-script:
jfx-deployment:
jar:
Copying 12 files to C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist\run53408212
jfx-project-run:
Executing C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist\run53408212\AccountingSnapshots.jar using platform C:\Program Files\Java\jdk1.8.0_31\jre/bin/java
this is chap 1
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1762)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1645)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1364)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$324(ContextMenuContent.java:1317)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer$$Lambda$147/1926554713.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/96639997.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1757)
... 43 more
Caused by: javafx.fxml.LoadException:
file:/C:/Users/john/Documents/NetBeansProjects/AccountingSnapshots/dist/run53408212/AccountingSnapshots.jar!/accountingsnapshots/AccountingSnapshots_1.fxml:16
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2435)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3208)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3169)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3142)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3118)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3098)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3091)
at accountingsnapshots.AccountingSnapshotsController.handleButtonAction(AccountingSnapshotsController.java:53)
... 53 more
Caused by: java.lang.IllegalArgumentException: Unable to coerce MenuButton#35398aab[styleClass=menu-button]'Home' to class javafx.scene.control.MenuItem.
at com.sun.javafx.fxml.BeanAdapter.coerce(BeanAdapter.java:495)
at javafx.fxml.FXMLLoader$PropertyElement.add(FXMLLoader.java:1387)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:784)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2817)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2526)
... 61 more
Corrected the second .fxml file, changing MenuButton to MenuItem. This is the result in the output section:
ant -f C:\\Users\\john\\Documents\\NetBeansProjects\\AccountingSnapshots jfxsa-run
init:
Deleting: C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\build\built-jar.properties
compile:
Detected JavaFX Ant API version 1.3
jfx-deployment:
jar:
Copying 12 files to C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist\run581163156
jfx-project-run:
Executing C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist\run581163156\AccountingSnapshots.jar using platform C:\Program Files\Java\jdk1.8.0_31\jre/bin/java
this is chap 1
Deleting directory C:\Users\john\Documents\NetBeansProjects\AccountingSnapshots\dist\run581163156
jfxsa-run:
BUILD SUCCESSFUL (total time: 19 seconds)
Any help appreciated
MenuItem is not a subclass of Node, so it doesn't inherit a getScene() method.
The simplest solution is just to call getScene() on any scene graph node which you know to be in the same scene as the menubar containing your menu item.
stage = (Stage) someNode.getScene().getWindow();
where someNode is any Node that you have injected into your controller with #FXML.
As you currently only have MenuItems injected into your controller, you need to inject some node for this purpose. The most natural one would be the root of the FXML. To do this, add a fx:id="root" attribute to your FXML's root element, and then just change the declaration of the root field in the controller so that it is injected:
#FXML
private Parent root ;
Then
stage = (Stage) root.getScene().getWindow();
should give you the current Stage, as needed.
This is an old thread, but the answer given was spot on
Here's a bit of code for anyone that's facing the same issues
Normally, I would just pass in a node to the stage object, but as has already been stated - a menu/menuItem cannot be converted to a node. Using the fx:id of the outermost node solves the problem. reportAnchorpane is the name of the (root) node for this respective FXML
public void gotoReports(ActionEvent e) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/Reports/Reports.fxml"));
Parent ReportManager = loader.load();
Scene ReportManagerScene = new Scene(ReportManager);
Stage window = (Stage)reportAnchorPane.getScene().getWindow();
window.setScene(ReportManagerScene);
window.show();
}
On the FXML
<AnchorPane fx:id="reportAnchorPane" prefHeight="500.0" prefWidth="800.0" styleClass="mainFxmlClass" fx:controller="Reports.ReportsController">
<stylesheets>
<URL value="#reports.css" />
</stylesheets>
<children>
<HBox fx:id="Menu" prefHeight="25.0" prefWidth="925.0">
<children>
<MenuBar fx:id="MenuBar" prefHeight="25.0" prefWidth="925.0">
<menus>
<Menu mnemonicParsing="false" text="Window" >
<items>
<MenuItem fx:id="miGotoReportsPage" mnemonicParsing="false" text="Reports" onAction="#gotoReports"/>
</items>
</Menu>
</menus>
</MenuBar>
</children>
</HBox>
</children>
</AnchorPane>