JavaFX: How to change scene (FXML) from MenuItem - javafx

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>

Related

change label text of FXML scene from another class via controller class

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++).

Exception running application application

This is my fx class
package application;
import java.io.File;
import java.net.URL;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("as1.fxml"));
primaryStage.setTitle("Abdul-Rahim University");
primaryStage.setScene(new Scene(root, 800, 500));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
and this is as1.fxml:
<?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.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.SeparatorMenuItem?>
<?import javafx.scene.effect.GaussianBlur?>
<?import javafx.scene.effect.MotionBlur?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="abd">
<children>
<MenuBar VBox.vgrow="NEVER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="New" />
<MenuItem mnemonicParsing="false" text="Open…" />
<Menu mnemonicParsing="false" text="Open Recent" />
<SeparatorMenuItem mnemonicParsing="false" />
<MenuItem mnemonicParsing="false" text="Close" />
<MenuItem mnemonicParsing="false" text="Save" />
<MenuItem mnemonicParsing="false" text="Save As…" />
<MenuItem mnemonicParsing="false" text="Revert" />
<SeparatorMenuItem mnemonicParsing="false" />
<MenuItem mnemonicParsing="false" text="Preferences…" />
<SeparatorMenuItem mnemonicParsing="false" />
<MenuItem mnemonicParsing="false" text="Quit" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Undo" />
<MenuItem mnemonicParsing="false" text="Redo" />
<SeparatorMenuItem mnemonicParsing="false" />
<MenuItem mnemonicParsing="false" text="Cut" />
<MenuItem mnemonicParsing="false" text="Copy" />
<MenuItem mnemonicParsing="false" text="Paste" />
<MenuItem mnemonicParsing="false" text="Delete" />
<SeparatorMenuItem mnemonicParsing="false" />
<MenuItem mnemonicParsing="false" text="Select All" />
<MenuItem mnemonicParsing="false" text="Unselect All" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About MyHelloApp" />
</items>
</Menu>
</menus>
</MenuBar>
<AnchorPane fx:id="ar" maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
<children>
<BorderPane fx:id="bo" layoutX="69.0" layoutY="32.0" prefHeight="200.0" prefWidth="200.0" />
<HBox fx:id="hb" focusTraversable="true" layoutX="70.0" layoutY="128.0" prefHeight="100.0" prefWidth="420.0" spacing="10.0">
<children>
<Button fx:id="st" mnemonicParsing="false" onAction="#handleButtonAction" text="Students" />
<Button fx:id="ac" mnemonicParsing="false" onAction="#handleButtonAction2" text="Academics" />
<Button fx:id="co" mnemonicParsing="false" onAction="#handleButtonAction3" text="Courses" />
</children>
<opaqueInsets>
<Insets bottom="11.0" left="11.0" right="11.0" top="10.0" />
</opaqueInsets>
<effect>
<GaussianBlur radius="1.75" />
</effect>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</HBox>
<Label fx:id="l1" contentDisplay="BOTTOM" layoutX="236.0" layoutY="26.0" text="University" textAlignment="CENTER" textOverrun="WORD_ELLIPSIS">
<font>
<Font name="Dubai Regular" size="33.0" />
</font>
<effect>
<MotionBlur radius="5.5" />
</effect>
</Label>
</children>
</AnchorPane>
</children>
</VBox>
I have tried to solve it alot and i cant if anyone can help me please solve this problem to me Exception running application applicatio i have tried to solve it alot and i cant if anyone can help me please solve this problem to me Exception running application applicatio
eclipse
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source) 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(Unknown Source) Caused by: javafx.fxml.LoadException:
/C:/Users/Abdurrahim/Desktop/mamoun/GUI/bin/application/as1.fxml:18
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:922)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
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 application.Main.start(Main.java:18)
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: java.lang.ClassNotFoundException: abd
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:920)
... 22 more Exception running application application.Main
my controller
package application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
public class FXMLDocumentController {
#FXML
private AnchorPane ar;
#FXML
private BorderPane bo;
#FXML
private HBox hb;
#FXML
private Button st;
#FXML
private Button ac;
#FXML
private Button co;
#FXML
private Label l1;
#FXML
void handleButtonAction(ActionEvent event) {
System.out.println("abd");
}
#FXML
void handleButtonAction2(ActionEvent event) {
System.out.println("abd");
}
#FXML
void handleButtonAction3(ActionEvent event) {
System.out.println("abd");
}
}
javafx
Here is the solution: fx:controller="application.FXMLDocumentController"

Exception in Application start method java with fxml

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)

onAction="#ClickedClickMe" not working in JavaFX FXML

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">

Exception in Application start method

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" ... >

Resources