fx:include with "resources" throws MissingResourceException but works in Java Code - java

I'm trying to use the resource tag inside fx:include in a FXML file.
What I don't understand is, that loading the resource bundle manually with ResourceBundle.getBundle() works completely fine.
I already tried a lot of variants in the fxml like:
"lang_challenges"
"wand555/github/io/challengesreworkedgui/lang_challenges"
package wand555.github.io.challengesreworkedgui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
public class ChallengeApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
ResourceBundle.clearCache();
ResourceBundle bundle = new ResourceBundleWrapper(ResourceBundle.getBundle("wand555/github/io/challengesreworkedgui/lang_challenges"));
System.out.println(bundle.getString("challenge.name")); // outputs "abc"
FXMLLoader loader = new FXMLLoader(ChallengeApplication.class.getResource("overview.fxml"), bundle);
Parent root = loader.load();
Scene scene = new Scene(root, 1000, 1000);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
// this class effectively does nothing, but it will be loaded by the
// application class loader
// instead of the system class loader.
private static class ResourceBundleWrapper extends ResourceBundle {
private final ResourceBundle bundle;
ResourceBundleWrapper(ResourceBundle bundle) {
this.bundle = bundle;
}
#Override
protected Object handleGetObject(String key) {
return bundle.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return bundle.getKeys();
}
#Override
public boolean containsKey(String key) {
return bundle.containsKey(key);
}
#Override
public Locale getLocale() {
return bundle.getLocale();
}
#Override
public Set<String> keySet() {
return bundle.keySet();
}
}
}
overview.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<AnchorPane prefHeight="500.0" xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="wand555.github.io.challengesreworkedgui.controllers.OverviewController">
<children>
<VBox>
<children>
<StackPane alignment="CENTER_LEFT">
<children>
<Button fx:id="exportButton" mnemonicParsing="false" onAction="#onExport" text="Export" />
</children>
</StackPane>
<HBox prefHeight="100.0" prefWidth="200.0" spacing="25.0">
<children>
<fx:include fx:id="challengesOverview" source="challenges/challenges_overview.fxml" resources="lang_challenges" charset="utf-8"/>
<Separator orientation="VERTICAL" prefHeight="200.0" />
<fx:include source="goals/goal_overview.fxml" />
<Separator orientation="VERTICAL" prefHeight="200.0" />
</children>
</HBox>
</children>
</VBox>
</children>
</AnchorPane>
The lang_challenges.properties contains a single key-value pair
challenge.name=abc
The `lang_challenges_de.properties' has the same content
challenge.name=abc
And this is the error message I'm getting
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at javafx.graphics#19/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics#19/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1082)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics#19/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
at javafx.graphics#19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: javafx.fxml.LoadException:
/Users/felixnaumann/Documents/ChallengesReworked/ChallengesReworkedGUI/target/classes/wand555/github/io/challengesreworkedgui/overview.fxml:21
at javafx.fxml#19/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2707)
at javafx.fxml#19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2685)
at javafx.fxml#19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml#19/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2516)
at challenges.reworked.gui/wand555.github.io.challengesreworkedgui.ChallengeApplication.start(ChallengeApplication.java:22)
at javafx.graphics#19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
at javafx.graphics#19/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics#19/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#19/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics#19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Caused by: java.util.MissingResourceException: Can't find bundle for base name lang_challenges, locale de_DE
at java.base/java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:2045)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1683)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1575)
at java.base/java.util.ResourceBundle.getBundle(ResourceBundle.java:1280)
at javafx.fxml#19/javafx.fxml.FXMLLoader$IncludeElement.processAttribute(FXMLLoader.java:1100)
at javafx.fxml#19/javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:230)
at javafx.fxml#19/javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:755)
at javafx.fxml#19/javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2808)
at javafx.fxml#19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2634)
... 9 more
Exception running application wand555.github.io.challengesreworkedgui.ChallengeApplication

Whew, finally figured it out after digging deep into the source code of ResourceBundle and ClassLoader.
How to fix it:
Really easy way:
Put your .properties files at the root of the resources folder. Then use it inside fxml
<fx:include source="second.fxml" resources="second_bundle"/>
and then everything should work fine.
However this approach is not suitable for larger projects which subdivide the resource bundles into different packages.
Using sub-packages in resources package
Give the fully qualified path name in the resources tag.
So for example if your package structure from src is com/example/demo/ (also in the resources folder) then use
<fx:include source="second.fxml" resources="com/example/demo/second_bundle"/>
But we are not done yet. You need to open the package to all modules in the module-info.java, explicitly using
opens com.example.demo to javafx.fxml;
does not work.
Instead you need to write
opens com.example.demo;
My two cents
Honestly to me this sounds like a bug.
I debugged the entire loading process and when the second_bundle is loaded from inside the fxml file, the caller module is javafx.fxml. And as the java doc for getResourceAsStream (which is internally called when loading) states:
A package name is derived from the resource name. If the package name is a package in the module then the resource can only be located by the caller of this method when the package is open to at least the caller's module. If the resource is not in a package in the module then the resource is not encapsulated.
So in theory opening your package to just javafx.fxml should work, but it doesn't...
Full demo project
This demo project uses sub-packages.
Project structure:
HelloApplication:
public class HelloApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
ResourceBundle bundle = new ResourceBundleWrapper(ResourceBundle.getBundle("test_bundle"));
System.out.println(bundle.getString("first.button")); // outputs "English/Deutsch"
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("first.fxml"), bundle);
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
// this class effectively does nothing, but it will be loaded by the
// application class loader
// instead of the system class loader.
private static class ResourceBundleWrapper extends ResourceBundle {
private final ResourceBundle bundle;
ResourceBundleWrapper(ResourceBundle bundle) {
this.bundle = bundle;
}
#Override
protected Object handleGetObject(String key) {
return bundle.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return bundle.getKeys();
}
#Override
public boolean containsKey(String key) {
return bundle.containsKey(key);
}
#Override
public Locale getLocale() {
return bundle.getLocale();
}
#Override
public Set<String> keySet() {
return bundle.keySet();
}
}
}
first.fxml:
<VBox alignment="CENTER" spacing="20.0" xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.demo.HelloController">
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
</padding>
<Label fx:id="welcomeText"/>
<Button text="%first.button" onAction="#onHelloButtonClick"/>
<fx:include source="second.fxml" resources="com/example/demo/second_bundle"/>
</VBox>
second.fxml:
<VBox alignment="CENTER" spacing="20.0" xmlns:fx="http://javafx.com/fxml">
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
</padding>
<Label fx:id="welcomeText"/>
<Button text="%second.button"/>
</VBox>
test_bundle.properties:
first.button=English
second_bundle.properties:
second.button=Hello
module-info.java:
module com.example.demo {
requires javafx.controls;
requires javafx.fxml;
opens com.example.demo;
exports com.example.demo;
}

Related

JavaFX 8: Custom controller from an inner class

The Problem
I am getting a ClassNotFoundException when trying to use the custom controller inside Joystick.java.
Here is my file hierarchy:
--view
----MainWindow.java
----mainWindow.fxml
----Joystick
------Joystick.java
------joystick.fxml
In mainWindow.fxml, I have the lines:
<?import view.Joystick.Joystick?>
...
<Joystick fx:id="manualJsk" layoutX="459.0" layoutY="195.0" />
I want to display my custom controller, but I keep getting the ClassNotFoundException, despite importing it.
Interestingly, everything works if I move the file to the view package:
--view
----MainWindow.java
----mainWindow.fxml
----Joystick.java
----Joystick
------joystick.fxml
... which makes me think the import is bad. Why could that be?
The Exception
java.lang.ClassNotFoundException: view.Joystick$Joystick
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at javafx.fxml/javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2931)
at javafx.fxml/javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2920)
at javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2861)
... 15 more
Edit:
Joystick Code:
public class Joystick extends Pane {
public Joystick() {
super();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("joystick.fxml"));
loader.setRoot(this);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
joystick.fxml
<fx:root xmlns:fx="http://javafx.com/fxml" type="javafx.scene.layout.Pane">
<children>
<Button text="Click Me"/>
</children>
</fx:root>

Internal NPE when launching JavaFX Application

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.

Connecting SQL Server with Java (javafx)

I have the setup below for the connection SQL Server with Java. Am also using javafx. I am very new to developing with Java. Note: I added the sqljdbc driver. I don't want to add main to DBConnection because am using the Connection method in the controller. Is there a way to fix this or how can I add main method without changing the connection method? Am getting error message:
Error Message
Error: Main method not found in class application.ConnectionDB, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane fx:controller="application.MainController" prefHeight="407.0" prefWidth="578.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label layoutX="123.0" layoutY="65.0" prefHeight="31.0" prefWidth="79.0" text="Date:" />
<Label layoutX="123.0" layoutY="138.0" prefHeight="25.0" prefWidth="127.0" text="Rim Current Value:" />
<Label layoutX="125.0" layoutY="210.0" text="Rim Sales Value for the Month:" />
<Label layoutX="123.0" layoutY="283.0" text="Rim Sold Cost Bought:" />
<TextField fx:id="txtdate" layoutX="123.0" layoutY="97.0" />
<TextField fx:id="txtcurvalue" layoutX="123.0" layoutY="163.0" />
<TextField fx:id="txtsalesvalue" layoutX="123.0" layoutY="234.0" />
<TextField fx:id="txtsoldcost" layoutX="123.0" layoutY="300.0" />
<Button layoutX="246.0" layoutY="340.0" mnemonicParsing="false" onAction="#Rmsubmit" prefHeight="25.0" prefWidth="103.0" text="Submit" />
</children>
</AnchorPane>
Connection Class
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConnectionDB
{
public static Connection dbConn() {
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver:[server name];database=SalesManager;user=[username];password=[password];encrypt=true;trustServerCert ificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
conn = DriverManager.getConnection(url);
}
catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(ConnectionDB.class.getName()).log(Level.SEVERE,null,ex);
}
return conn;
}
}
Controller
package application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javax.print.DocFlavor.URL;
public class MainController {
#FXML
public TextField txtdate;
#FXML
public TextField txtcurvalue;
#FXML
public TextField txtsalesvalue;
#FXML
public TextField txtsoldcost;
public Connection conn =null;
public PreparedStatement pat = null;
#FXML
public void Rmsubmit(ActionEvent actionEvent) {
String sqla = "Insert into RimCalc(Date, Rim_Vale,Rim_Sales,Rim_Cost) Values (?,?,?,?)";
String date = txtdate.getText();
String rim_value = txtcurvalue.getText();
String Rim_Sales = txtsalesvalue.getText();
String rim_cost = txtsoldcost.getText();
try {
pat = conn.prepareStatement(sqla);
pat.setString(1, date);
pat.setString(2, rim_value);
pat.setString(3, Rim_Sales);
pat.setString(4, rim_cost);
int i = pat.executeUpdate();
if(i==1) {
System.out.println("Insert Successfully");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initializer(URL url, ResourceBundle rb) {
conn = application.ConnectionDB.dbConn();
}
}
Java programs require a main method as an entry point in order to run. The standard definition of a main method is like this:
public static void main(String[] args) {
// First code of your program goes here
}
This main() method should include the code that starts your application and loads any interface elements for display.
A JavaFX application also needs to have a class that extends Application and override its start() method.
Here is a very quick and dirty example of one such class:
import javafx.application.Application;
import javafx.stage.Stage;
class Main extends Application {
public static void main(String[] args) {
launch(args); // Starts the JavaFX application and calls the start() method
}
#Override
public void start(Stage primaryStage) throws Exception {
// Here is where you'll initialize your views and such
}
}
I would recommend taking a few Java and JavaFX tutorials to get a feel for some of the basics before attempting more complicated tasks like connecting to databases.

JavaFx: parent.lookup returns null

I use osgi+cdi and I have the following code:
Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
} catch (IOException ex) {
Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
ComboBox comboBox=(ComboBox) parent.lookup("#testComboBox");
if (comboBox==null){
System.out.println("COMBOBOX NULL");
}else{
System.out.println("COMBOBOX NOT NULL");
}
And I have the following tasklist.fxml
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="440.0" prefWidth="757.0" xmlns="http://javafx.com/javafx/8.0.60-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.techsenger.testgo.core.adm.task.list.TaskDirListController">
<children>
<HBox>
<children>
<ToolBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" nodeOrientation="RIGHT_TO_LEFT" HBox.hgrow="SOMETIMES">
<items>
<ComboBox fx:id="testComboBox" maxWidth="1.7976931348623157E308" nodeOrientation="LEFT_TO_RIGHT" />
</items>
</ToolBar>
</children>
</HBox>
</children>
</VBox>
However parent.lookup("#testComboBox") returns null. How to explain it? I've checked the name of ID several times.
Instead of using a lookup, which will only work after the scene has been rendered, you can put the logic you need in your controller class. You can inject elements from the FXML file into the controller class by annotating them #FXML.
public class TaskDirListController {
#FXML
private ComboBox<...> testComboBox ;
public void initialize() {
System.out.println(testComboBox);
}
// ...
}
Lookups are generally not robust, and I would recommend avoiding using them. If you really need to access something defined in the FXML file from a class other than the controller, the first thing to do is to consider reorganizing things so that you don't need to do this: it really indicates that your overall design is wrong.
If you really need this for some reason, it's better to use the FXMLLoader's namespace than a lookup:
Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
ComboBox<?> comboBox = (ComboBox<?>) fxmlLoader.getNamespace().get("testComboBox");
System.out.println(comboBox);
} catch (IOException ex) {
Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
It is because you are trying to use lookup before showing the parent on the screen.
Pane root = FXMLLoader.load(getClass().getResource("tasklist.fxml"));
System.out.println(root.lookup("#testComboBox")); //returns null
primaryStage.setScene(new Scene(root));
primaryStage.show();
System.out.println(root.lookup("#testComboBox")); //returns
// ComboBox[id=testComboBox, styleClass=combo-box-base combo-box]

Error creating a custom FXML loader in Spring

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?

Categories

Resources