connecting scenebuilder UI fxml with javafx application - java

I have designed a UI in javafx scene builder, which has a simple button in stackpane.And I have named the controller class as simplecclass. I have saved the fxml as simple.fxml.
I have created a controller class in netbeans, which simply prints some msg on clicking the button.
In the NewFXBuilder java , I have loaded simple.fxml. Please find below the NewFXBuilder.java code.
package javafxapplication2;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
public class NewFXbuilder extends Application {
#Override
public void start(Stage primaryStage) {
try {
StackPane page = (StackPane) FXMLLoader.load(NewFXbuilder.class.getResource("simple.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("FXML is Simple");
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(NewFXbuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
Application.launch(NewFXbuilder.class, (java.lang.String[])null);
}
}
My simple.fxml,simplecclass.java and NewFXbuilder.java all resides in the same folder javafxapplication2.
while running NewFXBuilder.java, but it gives me the following error.
javafxapplication2.NewFXbuilder start
SEVERE: null
javafx.fxml.LoadException: java.lang.ClassNotFoundException: simplecclass

javafxapplication2.NewFXbuilder start SEVERE: null
javafx.fxml.LoadException: java.lang.ClassNotFoundException:
simplecclass
Looks like a problem in the FXML file. Make sure you import simplecclass in the FXML file.

The mistake I did was forgotten to add java packagename in the controller class name field in scene builder. It should have been packagename.simplecclass but I gave simplecclass alone,which is a mistake.

Related

getClass().getResource() throws a NullPointerException [duplicate]

This question already has an answer here:
How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?
(1 answer)
Closed 9 months ago.
I'm currently trying to start coding an app with IntelliJ and JavaFX, I have the following code :
package main.gui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.net.URL;
public class MainMenu extends Application {
#Override
public void start(Stage stage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("hello-view.fxml"));
URL url = getClass().getResource("hello-view.fxml");
System.out.println("URL = " + url);
Parent root = FXMLLoader.load(url);
Scene scene = new Scene(root,1920,1080);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
}
My file structure :
src/main/gui/MainMenu.java
src/main/gui/hello-view.fxml
And I get this exception :
Exception in Application start method
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: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/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
at javafx.graphics/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: Location is required.
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3324)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3287)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3255)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3227)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3203)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3196)
at main/main.gui.MainMenu.start(MainMenu.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
... 1 more
It outputs : URL = null
I've tried a lot of stuff that I've found on this site but without success...
Thank in advance for your help :)
To add a little more detail : I'm using Maven and I created the project with the
JavaFX project creation tool provided with IntelliJ.
I made it work by simply putting my fxml file into a ressources folder (src/main/resources) as suggested by #MatteoNNZ.
I tweaked a little bit the code to have the following :
package main.gui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.net.URL;
public class MainMenu extends Application {
#Override
public void start(Stage stage) throws Exception {
URL url = getClass().getClassLoader().getResource("hello-view.fxml");
System.out.println("URL = " + url);
Parent root = FXMLLoader.load(url);
Scene scene = new Scene(root,1920,1080);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
}
Obviously it could be simplified like this :
#Override
public void start(Stage stage) throws Exception {
// URL url = getClass().getClassLoader().getResource("hello-view.fxml"); |
// System.out.println("URL = " + url); | Remove these 3 lines
// Parent root = FXMLLoader.load(url); |
Scene scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("hello-view.fxml")),1920,1080);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
but it is very ugly.
Thank you everyone for your help and very quick answers :) .

Why it shows illegal character: '\ufeff' while importing javaFX stage [duplicate]

I have a main class which should call a JavaFX application (SimpleSun) to get Information from the user. Currently I create an Object of the JavaFX class and start it, but that doesn't seem to work. Does someone see the mistake in my work?
Here's my code and exception:
Main.java:
package ch.i4ds.stix.sim;
import ch.i4ds.stix.sim.grid.config.Configuration;
import ch.i4ds.stix.sim.grid.config.ConfigurationFromFile;
public class Main{
Configuration config;
public static void main(String[] args) {
ConfigurationFromFile config = new ConfigurationFromFile();
SimpleSun ss = new SimpleSun(config);
ss.show();
}
}
SimpleSun.java:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import ch.i4ds.stix.sim.grid.config.Configuration;
import ch.i4ds.stix.sim.grid.config.ConfigurationFromFile;
public class SimpleSun extends Application{
private Stage primaryStage;
Configuration configuration;
public SimpleSun(ConfigurationFromFile config) {
this.configuration = config;
}
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Simple Sun - Alpha");
System.out.println("Test");
try {
// Load the root layout from the fxml file
FXMLLoader loader = new FXMLLoader(
Main.class.getResource("view/RootLayout.fxml"));
BorderPane rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
// Exception gets thrown if the fxml file could not be loaded
e.printStackTrace();
}
}
public void show(){
launch();
}
}
Exception:
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class ch.i4ds.stix.sim.SimpleSun
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: ch.i4ds.stix.sim.SimpleSun.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
... 4 more
You must provide a constructor with no arguments when you extend application. So you could do something like:
public class SimpleSun extends Application {
private Stage primaryStage;
Configuration configuration;
public SimpleSun() {
this.configuration = Main.getConfig();
}
//...
and in your Main class:
public static Configuration getConfig() { return new ConfigurationFromFile(); }
Alternatively you can pass String parameters to the class with launch(args) and get them back in the SimpleSun class with getParameters().

Program will not run when turned into .jar

I have tried many methods over the last few days with no success...I've trawled through various Stackoverflow entries and to no avail...I must be missing something.
I have tried across three different IDEs...IntelliJ, Eclispe and Netbeans.
The problem is when trying to turn my program into an executable jar it is unable to run (either by double clicking or running through command).
When executing the following on command:
java -jar D:\Computing\Programming\Java\Projects\JavaFXGameMenu\out\artifacts\JavaFXGameMenu_jar\JavaFXGameMenu.jar
I get: Error: Could not find or load main class root.Main
When i run the same but with javaw instead.. i get not error message, but nothing happens either.
I am predominately using IntelliJ as its a JavaFX application that I am building.
This is the project hierarchy:
When creating the Artifact I choose the following based upon other threads:
I then re run this using: Java -jar D:\Computing\Executables\JavaFXGameMenu.jar
I get the following issue:
I have put the relevant environment variables into my system and Path and I am using jre1.8.0_144.
Any help with tracking down what the problem could be is greatly appreciated
Code below...but this fully compiles and runs within IDE without errors...the problem is when its turned into a .jar and ran from command.
package root;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main extends Application {
private double width = 1920;
private double height = 1080;
private Parent createContent(){
Pane root = new Pane();
root.setPrefSize(width, height); //W:860 H:600
ImageView imgLogo = null;
ImageView bottomlogo = null;
MenuItem newGame = new MenuItem("NEW GAME");
MenuItem continueGame = new MenuItem("CONTINUE");
MenuItem friends = new MenuItem("FRIENDS");
MenuItem settings = new MenuItem("SETTINGS");
MenuItem store = new MenuItem("STORE");
MenuItem exit = new MenuItem("EXIT");
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/dark.jpg"))) {
ImageView img = new ImageView(new Image(is));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/logo.png"))) {
imgLogo = new ImageView(new Image(is));
imgLogo.setX(1000);
imgLogo.setY(100);
imgLogo.setFitWidth(600);
imgLogo.setFitHeight(300);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/SteamAgony.png"))) {
bottomlogo = new ImageView(new Image(is));
bottomlogo.setX(100);
bottomlogo.setY(800);
bottomlogo.setFitHeight(200);
bottomlogo.setFitWidth(200);
bottomlogo.setOpacity(0.7);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
MenuBox menu = new MenuBox(
newGame,
continueGame,
friends,
settings,
store,
exit);
menu.setTranslateX(width / 3.4);
menu.setTranslateY(height / 2.5);
settings.setOnMouseClicked(event -> new SceneCreator().createScene(200,300));
exit.setOnMouseClicked( event -> Platform.exit());
root.getChildren().addAll(menu, imgLogo, bottomlogo);
return root;
}
#Override
public void start(Stage primaryStage) throws Exception{
Scene scene = new Scene(createContent());
primaryStage.setScene(scene);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
#Override
public void stop(){
//TODO
}
public static void main(String[] args) {
launch(args);
}
}
The error is at Main.createContent line 102. Maybe you forgot to initialize the child node (I'm not really familiar with JavaFX).
As #cedrikk mentioned, the problem is related to your code in Main.createContent.
You said the problem is when trying to run the jar as an executable -
did you try to run it within the IDE? If not - you should try to, and while at it - debug it to help you find the problem. Just right click your Main class and choose debug.
Regarding running it with javaw, the reason you got no error messages is because javaw executes java programs without a console - where you would normally get error messages unless using some logging solution.
You are adding a null element as a child of a Pane, causing the null pointer issue you are facing, if you use the debugger you'll be able to find where the variable that shouldn't be null is being set to null.
Edit - after code added
You are seeing 2 fields in try catches (imageLogo, bottomLogo), and adding them even if they fail, which adds nulls, causing the error.
You use a relative path for the images, this is probably the issue, are you running the jar from the project root? If not you could put the absolute path, but using resources would be more reliable, and allow the jar to run on different computers.
The problem was down to declaring inputStreams.
This works for both in IDE and running from jar:
String bgImg = "root/resources/dark.jpg";
URL bgImgPath = Main.class.getClassLoader().getResource(bgImg);
ImageView img = new ImageView(new Image(bgImgPath.toExternalForm()));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
Compared to what I had before:
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/dark.jpg"))){
ImageView img = new ImageView(new Image(is));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
}catch (IOException e) {
System.out.println("Could not load");
}
The changes to the paths, were from where I tried adding the resource folder to the root folder instead of within src.

JavaFx runnable JAR export is not working

I've made a simple dictionary using JavaFX. I've used a SQLite Database and some pictures into my application. I exported the application as a runnable JAR file using e(fx) Eclipse. I followed the steps described here - https://wiki.eclipse.org/Efxclipse/Tutorials/Tutorial1.
After exporting I opened the .JAR file. It opened successfully but wasn't working properly. It wasn't showing the results from the database and images.
When I ran the application into Eclipse workspace before building & exporting, it worked fine.
Where is the problem? How do I fix it?
Here is the code for the Controller Class function:
package imran.jfx.application;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
public class Application_Controler implements Initializable{
#FXML
private HBox hBox;
#FXML
private Label searchLabel;
#FXML
private TextField searchWord;
#FXML
private VBox vBox;
#FXML
private Text BanglaMeaning;
#FXML
private TextArea bnMeaningTxt;
#FXML
private Text bAcaMeaning;
#FXML
private ScrollPane bAcaMeaningImg;
#FXML
private Label footerLabel;
ResultSet result;
PreparedStatement doQuery;
Connection conn;
String query;
#Override
public void initialize(URL location, ResourceBundle resources) {
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url="jdbc:sqlite:src/imran/ankurdb/meaning/bn_words.db";
try
{
conn = DriverManager.getConnection(url);
}
catch (SQLException e) {
e.printStackTrace();
}
}
#FXML
void showMeaning(ActionEvent event) throws Exception {
bnMeaningTxt.clear();
String text=searchWord.getText();
query = "select en_word,bn_word from words where en_word='"+text+"'";
doQuery = conn.prepareStatement(query);
result = doQuery.executeQuery();
int i=0;
while (result.next())
{
if(i==0)
{
bnMeaningTxt.appendText(result.getString(1) + "\t\t" + result.getString(2));
i++;
}
else
bnMeaningTxt.appendText(" , "+result.getString(2));
}
File file = new File("src/imran/bnacademy/meaning/"+text);
Image image = new Image(file.toURI().toString());
bAcaMeaningImg.setContent(new ImageView(image));
}
}
There are multiple problems here.
You are trying to create a database file inside your project. This is not going to work when you have packaged your project as a jar. You should give it a url outside your project. The database files should be placed always outside the project, so that when you package your project as a jar, they can still be created, read and written to.
If the images are present inside your jar, you cannot use io.File to load images. You need to use the class loader to load them instead.
Code
URL url = getClass().getResource("/imran/bnacademy/meaning/" + text);
Image image = new Image(url.toExternalForm());

Trying to call a JavaFX application from Java... NoSuchMethodException

I have a main class which should call a JavaFX application (SimpleSun) to get Information from the user. Currently I create an Object of the JavaFX class and start it, but that doesn't seem to work. Does someone see the mistake in my work?
Here's my code and exception:
Main.java:
package ch.i4ds.stix.sim;
import ch.i4ds.stix.sim.grid.config.Configuration;
import ch.i4ds.stix.sim.grid.config.ConfigurationFromFile;
public class Main{
Configuration config;
public static void main(String[] args) {
ConfigurationFromFile config = new ConfigurationFromFile();
SimpleSun ss = new SimpleSun(config);
ss.show();
}
}
SimpleSun.java:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import ch.i4ds.stix.sim.grid.config.Configuration;
import ch.i4ds.stix.sim.grid.config.ConfigurationFromFile;
public class SimpleSun extends Application{
private Stage primaryStage;
Configuration configuration;
public SimpleSun(ConfigurationFromFile config) {
this.configuration = config;
}
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Simple Sun - Alpha");
System.out.println("Test");
try {
// Load the root layout from the fxml file
FXMLLoader loader = new FXMLLoader(
Main.class.getResource("view/RootLayout.fxml"));
BorderPane rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
// Exception gets thrown if the fxml file could not be loaded
e.printStackTrace();
}
}
public void show(){
launch();
}
}
Exception:
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class ch.i4ds.stix.sim.SimpleSun
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: ch.i4ds.stix.sim.SimpleSun.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
... 4 more
You must provide a constructor with no arguments when you extend application. So you could do something like:
public class SimpleSun extends Application {
private Stage primaryStage;
Configuration configuration;
public SimpleSun() {
this.configuration = Main.getConfig();
}
//...
and in your Main class:
public static Configuration getConfig() { return new ConfigurationFromFile(); }
Alternatively you can pass String parameters to the class with launch(args) and get them back in the SimpleSun class with getParameters().

Categories