This is probably a simple error, but I can't figure it out. I can call getText on TextArea controls just fine, but TextField controls are constantly thowing an InvocationTargetException error. They are both defined in the same way and I've triple checked the FX IDs and controller is correct. Not sure what else could cause this. Please help!
Relevant FXML - Root Node
<VBox prefHeight="500.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="api.LayoutController">
Field FXML
<TextField fx:id="apitoken" text="mytopsecrettoken" GridPane.columnIndex="1">
<GridPane.margin><Insets /></GridPane.margin></TextField>
Controller:
public class LayoutController implements Initializable {
#FXML
private TextArea result,data;
private TextField apitoken,object;
#FXML
private void submit(ActionEvent event) {
result.setText(apitoken.getText());
}
Exception information:
Executing C:\Users\XXX\Documents\NetBeansProjects\API\dist\run1375954609\API.jar using platform C:\Program Files\Java\jdk1.8.0_05\jre/bin/java
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1768)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1651)
Related
So basically I began a dummy JavaFX project just to achieve a minimalistic example for my actual problem. But now I am not even able to run that minimalistic project anymore and do not receive enough error information to actually google it myself out. So right now, when I run the code, I receive the given error stack, which does not lead me anywhere.
I am using IntelliJ. JavaFX libraries are set correctly and VM Options set to:
--module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml
On top, when I run the code, those errors pop up in console, but the application seems to still be running, because I need to press the Red Stop Button of IntelliJ to actually stop it.
Has anyone some guess, what goes wrong here? I am not experienced enough to follow those errors, since they do not point into my code, but rather into some Deep Java code.
The Exception:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.NullPointerException
at java.base/java.lang.reflect.Method.invoke(Method.java:559)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
... 5 more
Main.java:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
private Stage rootStage;
public BorderPane mainWindow;
public AnchorPane left;
public AnchorPane bottom;
#Override
public void start(Stage primaryStage) throws Exception {
this.rootStage = primaryStage;
loadMainWindow();
}
public void loadMainWindow() throws IOException {
FXMLLoader loaderMainWindow = new FXMLLoader(Main.class.getResource("MainWindow.fxml"));
mainWindow = loaderMainWindow.load();
FXMLLoader loaderLeft = new FXMLLoader(Main.class.getResource("Left.fxml"));
left = loaderLeft.load();
mainWindow.setLeft(left);
//mainWindow.setBottom(bottom);
Scene scene = new Scene(mainWindow);
rootStage.setScene(scene);
rootStage.show();
}
public void main(String[] args) {
launch(args);
}
}
MainWindow.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.MainWindowController" />
MainWindowController:
package sample;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
public class MainWindowController implements Initializable {
private Main main;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void setMain(Main main) {
this.main = main;
}
}
Left.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="100.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.LeftController">
<children>
<Button fx:id="button" layoutX="237.0" layoutY="169.0" mnemonicParsing="false" onAction="#buttonClick" text="Button" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" />
</children>
</AnchorPane>
LeftController.java:
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;
public class LeftController implements Initializable {
#FXML
private Button button;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void buttonClick(javafx.event.ActionEvent actionEvent) {
System.out.println("Some Stuff");
}
}
Solution
The error you're getting is caused by your main(String[]) method not being static. If you make it static then the error will go away.
Some Explanation
JavaFX offers the ability to launch applications without providing a main method, so long as the main class is a subclass of Application. However, developers can still include a main method which means this special launch functionality has to handle that situation gracefully. In other words, an explicit main method present in the Application subclass must act like the entry point of the application from the developer's point of view. Nonetheless, behind the scenes some deep internal class has become the "real" main class.
To do this, the main method is located—if present at all—via Class#getMethod(String,Class...) which, while only returning public methods, doesn't distinguish between static and non-static methods. If found, Method#invoke(Object,Object...) is used to invoke the main method reflectively. The first argument of invoke is the instance that the method should be invoked on; in the case of static methods the value is null. Unfortunately, the code assumes the method it found is static which causes a NullPointerException to be thrown—you can't call an instance method on a null "instance".
Update: This issue has been submitted on GitHub (#570) and subsequently JBS (JDK-8230119). The current idea is to emit a warning rather than throw the NullPointerException. However, the functionality that allows launching without a main method may be deprecated in a future release, which will affect how this issue is addressed.
This is my first program in javafx. I have just created a AnchorPane with the help of scene Builder. what I want from this is when we click any where in the AncherPane it should show the coordinate point of that pixel.
This is the controller class
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
public class AxisController implements Initializable{
#FXML
private AnchorPane anchr;
#Override
public void initialize(URL location, ResourceBundle resources) {
assert anchr != null : "fx:id=\"anchr\" was not injected: check your FXML file 'AxisFxml.fxml'.";
anchr.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println(event.getX());
System.out.println(event.getY());
}
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane fx:id="anchr" onMouseClicked="#initialize" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AxisController">
<!-- TODO Add Nodes -->
</AnchorPane>
Error Message
javafx.fxml.LoadException: Error resolving onAction='#initialize', either the event handler is not in the Namespace or there is an error in the script.
/home/xyz/workspace/AxisExample/bin/application/AxisFxml.fxml:9
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 application.AxisMain.start(AxisMain.java:16)
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.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
at java.lang.Thread.run(Thread.java:745)
You have a couple of misunderstandings here.
The methods whose names you set as values to the "event handler attributes", such as onMouseClicked, are the methods that will be invoked when those events happen. They should just contain the code that you want to be executed when, in this case, the mouse is clicked. You should not register event handlers in these methods. (This would mean: "when the anchor pane is clicked, register an event handler for the anchor pane being clicked", which is clearly not what you intend.)
As a consequence of this, methods that are registered in the FXML as event handler methods should take a single parameter of the correct event type. (It is also allowable to take no parameters, if you don't need the event object - a common scenario.)
The error you are getting is because the method you have declared to be the event handler (initialize(), which has a completely different role), has the wrong signature: it take the wrong number (and type) of parameters.
Secondly, the initialize() method, which may either be declared with no parameters, or be declared with parameters of type URL and ResourceBundle, is invoked during the process of loading the FXML. This happens after all the #FXML-annotated fields have been injected, but before the root of the UI is returned from the call to FXMLLoader.load(). Thus it's safe to access #FXML-annotated fields here: they will have been properly initialized.
So there are two distinct ways of registering event handlers.
Either:
Define a method in the controller, and reference it in the FXML file:
<AnchorPane fx:id="anchr" onMouseClicked="#handleClick" ... fx:controller="application.AxisController">
<!-- TODO Add Nodes -->
</AnchorPane>
and then
public class AxisController implements Initializable{
#FXML
private AnchorPane anchr;
#Override
public void initialize(URL location, ResourceBundle resources) {
assert anchr != null : "fx:id=\"anchr\" was not injected: check your FXML file 'AxisFxml.fxml'.";
}
#FXML
private void handleClick(MouseEvent event) {
System.out.println(event.getX());
System.out.println(event.getY());
}
}
Or:
Remove the onMouseClicked attribute from the FXML file, and register the event handler in the initialize() method. (So the controller is exactly as you have it.)
I would assume that the problem lies in your anchorPane on your FXML, have you assigned a function to the anchorPane for a click event on your FXML? if you have you can set the function for that event by doing the same as if you where initializing the variable for example:
#FXML
private void restartExited() {
exitedTransition(0, "circle", null, buttonCirc);
}
you can tell your anchorPane in the FXML to do this function when it is clicked or mouseOver for example, you do not need to set it in the controller as well as the FXML.
Or in your case:
#FXML
private void initialize() {
anchr.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println(event.getX());
System.out.println(event.getY());
}
});
}
Or you could remove the reference to onClick on the AnchorPane in your FXML and use your current code.
EDIT
Can I ask where you are defining the stage and the FXML to load to the stage, is this your stage initializer for your application or the controller for the FXML?
I make a simple JavaFX application. In this application there is a treetable with 2 columns and a check box. If check box is selected column 2 will be visible, otherwise not visible. To do this I bound tree table column visible property to checkbox selected property. When I click the check box column state change but at the same time gives.
Caused by: java.lang.RuntimeException: TreeTableColumn.visible : A
bound value cannot be set.
If I use bidirectional binding I don't get this error. But I don't need bidirectional binding. Is it a bug or I don't use bind correctly? Please use below code to reproduce this error. I use jdk1.8.0_111.
JavaFXApplication.java
package test;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXApplication 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
package test;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
public class FXMLDocumentController implements Initializable {
#FXML
private TreeTableView<?> table;
#FXML
private CheckBox box;
#FXML
private TreeTableColumn<?, ?> c2;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
c2.visibleProperty().bind(box.selectedProperty());
}
}
FXMLDocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.TreeTableColumn?>
<?import javafx.scene.control.TreeTableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="390.0" prefWidth="452.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.65" fx:controller="javafxapplication2.FXMLDocumentController">
<children>
<TreeTableView fx:id="table" layoutX="2.0" prefHeight="390.0" prefWidth="149.0">
<columns>
<TreeTableColumn prefWidth="75.0" text="C1" />
<TreeTableColumn fx:id="c2" prefWidth="75.0" text="C2" visible="false" />
</columns>
</TreeTableView>
<CheckBox fx:id="box" layoutX="234.0" layoutY="77.0" mnemonicParsing="false" text="CheckBox" />
</children>
</AnchorPane>
I think this actually is not a bug. It's definitely mysterious and unexpected behavior though. Part of the problem is that the binding conflict is coming from TableHeaderRow, which is created by the skin at display time.
The TableHeaderRow is responsible for rendering all the column headers, and it includes this built-in button for a menu that, by default, is a radio selection list of columns to show/hide:
As a result, the TableHeaderRow creates a bidirectional binding between these menu entries' selection state and each column's visible property.
It actually is possible to undo this binding but I found it annoying since the TableHeaderRow is null until the TableView is displayed. But, adapting this solution to access the TableHeaderRow, we can do something like:
TableHeaderRow headerRow = ((TableViewSkinBase) tableView.getSkin()).getTableHeaderRow();
try {
// get columnPopupMenu field
Field privateContextMenuField = TableHeaderRow.class.getDeclaredField("columnPopupMenu");
// make field public
privateContextMenuField.setAccessible(true);
// get context menu
ContextMenu contextMenu = (ContextMenu) privateContextMenuField.get(headerRow);
for (MenuItem menuItem : contextMenu.getItems()) {
// Assuming these will be CheckMenuItems in the default implementation
BooleanProperty selectedProperty = ((CheckMenuItem) menuItem).selectedProperty();
// In theory these menu items are in parallel with the columns, but I just brute forced it to test
for (TableColumn<?, ?> tableColumn : tableView.getColumns()) {
// Unlink the column's visibility with the menu item
tableColumn.visibleProperty().unbindBidirectional(selectedProperty);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
// Not strictly necessary but we don't want to be misleading :-p
tableView.setTableMenuButtonVisible(false);
But here's the kicker: you have to do this every time a column's visibility changes, because the TableHeaderRow has a listener that rebuilds the menu, and re-links the properties, every time a column is shown.
You could, of course, find a way to disable that listener.. but clearly this is already ridiculous and probably unnecessary.
Anyway, as you noted:
If I use bidirectional binding I don't get this error. But I don't need bidirectional binding.
I think the second statement isn't technically true: your use case doesn't require bidirectional binding, but it is actually appropriate here since there are other properties already linked with a column's visibility.
So, I would use bidirectional binding.
My application is throwing a NullPointer exception when I call the variable empName.
ResultSet result = stmnt.executeQuery("select FirstName, LastName from emp_info where EmployeeID "
+ "= '" + empID + "'");
// while(result.next()){
// empName.setText("result.getString(1));
// }
empName.setText("asdf");
rootLayout.setCenter(controlData);
connection.close();
}
}
It should be able to run fine since I initialize the Text variable like so:
#FXML
public Text empName;
Also when I use scenebuilder, it sometimes shows the fx:id empName but when I exit out of it and reopen it doesn't show it. I think that's where the problem is. My xml file is:
<AnchorPane prefHeight="300.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="studentempsignin.MainPage_Controller">
<children>
<BorderPane prefHeight="300.0" prefWidth="500.0">
<center>
<Text fx:id="empName" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
</children>
</AnchorPane>
The exception I get is:
SEVERE: null
java.lang.NullPointerException
at studentempsignin.MainPage_Controller.signingIn(MainPage_Controller.java:190)
at studentempsignin.SignIn_Controller.lambda$0(SignIn_Controller.java:66)
at studentempsignin.SignIn_Controller$$Lambda$143/575703892.handle(Unknown Source)
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.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
Edit:
The method empIDAccess is being called when I click the signIn button:
signInBtn.setOnAction((e) -> {
try {
//used dbaseDriver...idk why
// DBaseDriver connect = new DBaseDriver("jdbc:mysql://localhost:3306/AUStudentEmployees",
// "kheneahm", "kennygoham");
String empID = empIDField.getText();
MainPage_Controller empIDAccess = new MainPage_Controller();
empIDAccess.signingIn(empID, invalidID, signInBtn);
} catch (Exception ex) {
Logger.getLogger(SignIn_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
});
You're creating a new controller instance. The FXMLLoader creates a controller instance and initializes the #FXML-annotated fields in that instance, when you load the FXML file. Those fields won't be initialized in the new instance you create (and even if they were, they wouldn't refer to the same objects displayed in the UI).
You need to get a reference to the controller that is created when you load the FXML.
I've been trying to move my JavaFx application to Spring to make use of dependency injecton. The project has become too big to move items between classes manually.
The code does not show any red error highlights on my netbeans IDE, but when I run I keep getting this error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController' defined in class wakiliproject.controllerinjection.SampleAppFactory: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public wakiliproject.controllerinjection.controllers.HomeController wakiliproject.controllerinjection.SampleAppFactory.homeController() throws java.io.IOException] threw exception; nested exception is javafx.fxml.LoadException: Base location is undefined.
I have it like this:
public class SampleApp extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) throws Exception {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(SampleAppFactory.class);
Group box = new Group();
HomeController homeController = context.getBean(HomeController.class);
box.getChildren().add(homeController.getView());
Scene scene = new Scene(box, 600, 200);
stage.setScene(scene);
stage.setTitle("JFX2.0 Sprung");
stage.show();
}
}
--
#Configuration
public class SampleAppFactory {
#Bean
public HomeController homeController() throws IOException {
return (HomeController) loadController("/resources/fxml/Home.fxml");
}
protected Object loadController(String url) throws IOException {
InputStream fxmlStream = null;
try {
fxmlStream = getClass().getResourceAsStream(url);
FXMLLoader loader = new FXMLLoader();
loader.load(fxmlStream);
return loader.getController();
} finally {
if (fxmlStream != null) {
fxmlStream.close();
}
}
}
}
--
public class HomeController {
#FXML
private AnchorPane view;
public AnchorPane getView() {
return view;
}
}
An extract of the FXML file looks something like this:
<?xml version="1.0" encoding="UTF-8"?>
<AnchorPane fx:id="view" prefHeight="654.0" prefWidth="900.0" styleClass="AnchorPane" visible="true" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="wakiliproject.controllerinjection.controllers.HomeController">
<children>
<Pane id="wrapperPane" prefHeight="600.0" prefWidth="700.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Pane id="top" layoutX="-1.0" layoutY="3.0" prefWidth="879.0" styleClass="appNav" visible="true">
<children>
<HBox id="HBox" alignment="CENTER" layoutX="12.0" layoutY="6.0" spacing="0.0">
<children>
<Label prefHeight="32.0" prefWidth="32.0" styleClass="titleBarHome" />
<Label prefHeight="32.0" prefWidth="32.0" styleClass="titleBarPublisher" />
</children>
</HBox>
It looks like you need to set the location of your FXML file on the FXMLLoader. This can be the case if, for example, your FXML file requires resolving relative locations. Using the FXMLLoader.load(URL) method does not set the location. Try
protected Object loadController(String url) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource(url));
loader.load();
return loader.getController();
}
instead of the current implementation you have.
Incidentally, have you looked at afterburner.fx as a (much more lightweight) alternative to Spring for dependency injection in JavaFX?