Java LibGDX Texture gives null pointer exception - java

I've been using LibGDX for a project and whenever i declare a Texture it gives :
Exception in thread "main" java.lang.NullPointerException
at com.fistbump.patman.test.main(test.java:18)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140
The code is :
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
public class test {
public static void main(String[] args){
Texture text = new Texture(Gdx.files.internal("Path.png"));
OR
Texture text = new Texture("Path.png");
}
}
I am really stuck here . Thanks in advance

You cant use (the majority of) libGDX before it is initialized. This is in or after the create method of your ApplicationListener (or ApplicationAdapter or Game if your prefer).
See also: https://github.com/libgdx/libgdx/wiki/The-life-cycle

Related

JavaFX ListView Null Pointer when Adding to List [duplicate]

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 3 years ago.
Edit: Static's removed. Still getting the same error
I've created a GUI with a Listview in Scene builder and now I'm trying to populate the Listview with some Strings.
I'm using 2 classes at the moment. Here are 2 cut down versions of the scripts for easier reading
MainController:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class MainController extends Application
{
#Override
public void start(Stage primaryStage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("IntelligentSystems.fxml"));
primaryStage.setTitle("Intelligent Systems Agent Program");
primaryStage.setScene(new Scene (root));
primaryStage.show();
GUIController GUIList = new GUIController();
GUIList.DoList.add("agentCtrl");
GUIList.DoList.add("DeliveryAgent");
GUIList.PopulateAgentList();
}
public static void main (String[] args)
{
launch(args);
}
}
and the second Class, GUIController:
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
public class GUIController {
//List View variables.
#FXML
public ListView AgentsList;
#FXML
public ObservableList<String> DoList= FXCollections.observableArrayList();
#FXML
public void PopulateAgentList()
{
AgentsList.setItems(DoList);
}
}
Currently, I've set the fxId of the Listview to "AgentsList" in the fxml file.
<ListView fx:id="AgentsList" layoutX="15.0" layoutY="39.0" prefHeight="200.0" prefWidth="86.0" />
Whenever I run the program in IntelliJ, it always returns a java.lang.NullPointerException around the "AgentsList.setItems(_doList);" line.
I'm completely lost as to why it can't add to the list. Not helped that I haven't been using Java for long as I've mostly worked with C#.
Edit: Exception Stack Trace:
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:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
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:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.NullPointerException
at GUIController.PopulateAgentList(GUIController.java:26)
at MainController.start(MainController.java:57)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
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:174)
... 1 more
Exception running application MainController
Process finished with exit code 1
Your #FXML annotated fields are static, which is not supported by JavaFX, as it is desinged to create/load multiple instances of the same fxml file/controller class. If you are unfamiliar with what 'static' actually means, you can refer to What is the difference between a static method and a non-static method?.
As for how you get the correct controller instance, you need to load the fxml file a little bit different.
FXMLLoader loader = new FXMLLoader(getClass().getResource("IntelligentSystems.fxml"));
Parent root = loader.load(); // must be called before getting the controller!
GUIController controller = loader.getController();
Now you can use the controller variable to access the fields in a non-static way.

JavaFX issue with static keyword; with Minimal, Complete, and Verifiable example

Good day,
When I run this Code:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class mcve extends Application {
static Label myScore = new Label("Test");
static Rectangle rect = new Rectangle(0,0,10,10);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
myScore.setTextFill(Color.WHITE);
myScore.setLayoutY(20);
myScore.setLayoutX(200);
myScore.setFont(new Font("Arial", 30));
myScore.setText("0");
rect.setFill(Color.WHITE);
final Group group = new Group(myScore,rect);
Scene scene = new Scene(group, 500, 500, Color.BLACK);
stage.setScene(scene);
stage.show();
}
}
it creates the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at mcve.<clinit>(mcve.java:11)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:122)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:273)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:268)
at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:550)
at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
at javafx.scene.control.Control.<clinit>(Control.java:87)
... 4 more
However if I remove the static keyword before Label at the top, the code runs just fine.
My question is: Why does the error occur when creating a static Label but not a static Rectangle? I want the Label to be static and not an object of a class.
Why does the error occur when creating a static Label but not a static Rectangle?
Essentially, this is a matter of initialization order. The UI platform needs to be properly initialized when creating Node objects. Potentially, it could also happen with a Rectangle, but most likely a Label (which is a Control) relies even more on a properly initialized platform. In this particular case, the difference is that Shape objects do not require CSS, while Control objects do. This causes the platform methods to be called as seen in the stack trace, at a point when the toolkit is not yet initialized.
The static class member is initialized when class mvce is loaded. This is done before the main() method is called, and hence before the launch() method is called. The platform is not initialized yet at this point.
The non-static member, on the other side, is initialized when class mvce is instantiated. The class mvce is instantiated internally by the launch() method, after the toolkit has been properly initialized.
Also, there is usually no reason to use static references. Just use a member.
Have you tried to just declare the static label, but instanciate and set it later on in the start() method? This should work, too.

LibGDX Box2DLights throws error on render

I am trying to get a Box2D PointLight to render on the screen, but upon rendering, it throws an exception. I have revised the API and the Box2D User Manual, as well as watched videos on the topic, but have yet to find a solution to my problem. Here is my code and the error.
package com.mygdx.test;
import box2dLight.PointLight;
import box2dLight.RayHandler;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
public class Test extends ApplicationAdapter {
/** the camera **/
OrthographicCamera camera;
RayHandler rayHandler;
World world;
#Override
public void create() {
camera = new OrthographicCamera(48, 32);
camera.update();
world = new World(new Vector2(0, -10), true);
rayHandler = new RayHandler(world);
new PointLight(rayHandler, 32);
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(Gdx.graphics.getDeltaTime(), 8, 3);
rayHandler.setCombinedMatrix(camera.combined);
rayHandler.updateAndRender();
}
And the error:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/Texture;
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:127)
Caused by: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/Texture;
at box2dLight.LightMap.gaussianBlur(LightMap.java:76)
at box2dLight.LightMap.render(LightMap.java:37)
at box2dLight.RayHandler.render(RayHandler.java:328)
at box2dLight.RayHandler.updateAndRender(RayHandler.java:262)
at com.mygdx.test.Test.render(Test.java:33)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
I had the same issue with a newly generated libgdx project, however updating the box2dlights version from 1.3 to 1.4 solved this error for me.
Have you tried using this method?
new PointLight(rayHandler, RAYS_NUM, new Color(1,1,1,1), lightDistance, x, y);
I have also noticed, you should do
world.step();
at the end of the render() method. Probably wont fix the problem, but i just noticed

Java FX Exception (Media Player Application)

I'm just starting to use Java FX and cannot for the life of me figure out why this exception keeps occurring.
I have 2 classes. One called Main and the other called Player. Here is what they each look like....
Main Class
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Player player = new Player("/Applications/Nacho.mp4");
Scene scene = new Scene (player, 720, 480, Color.BLACK);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Player Class
package application;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
public class Player extends BorderPane {
Media media;
MediaPlayer player;
MediaView view;
Pane nPane;
public Player(String file){
media = new Media(file);
player = new MediaPlayer(media);
view = new MediaView(player);
nPane = new Pane();
nPane.getChildren().add(view);
setCenter(nPane);
player.play();
}
}
Here is what the compiler spits out when I run the program...
START
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:497)
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:497)
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$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1323468230.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'Applications/Nacho.mp4'
at com.sun.media.jfxmedia.locator.Locator.(Locator.java:211)
at javafx.scene.media.Media.(Media.java:391)
at application.Player.(Player.java:16)
at application.Main.start(Main.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$54/1046396900.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/186276003.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$49/287662571.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/237061348.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application application.Main
FINISH
I know that the issue occurs as soon as the Player object is instantiated in Main. As soon the Player object uses it's constructor and creates a Media object, which gets passed the String file location, that's when I get the error. I ran the program with an empty constructor for the Player object and it ran fine so the issue is clearly in my Player Class, again when the Media object is instantiated. Am I passing the correct parameters? "/Applications/Nacho.mp4"
If someone can please tell me how to fix this, I would greatly appreciate it. I literally can't move forward with this project otherwise. Thank you!
Nevermind, I figured it out, the problem was passing the parameter to the Media object. I'm used to C++ syntax and did not realize that the proper way to do it is
media = new Media("file:///Applications/Nacho.mp4");
This error usually occurs due to wrongly input of the file address. The correct way to write the address is file:///C:/abc.mp4.
More clearly:
Object b = new Object("file:///C:/abc.mp4");

Java- java.lang.NoClassDefFoundError, classpath not the issue

I'm writing a program for homework and running into an issue I can't seem to resolve. The problem involves simulating the probabilities of a randomwalk ending on any given node (just background, not really relevant to the problem). I've written my own class that uses a hash map to hold node objects (UndirectedGraph and NodeEntry respectively). I've also written a test harness.
Originally all these were in one file but I decided to move the UndirectedGraph and NodeEntry to a separate package...cause that seems like the right thing to do. I've gotten everything fixed up so that testHarness will compile but at runtime I get the following:
Exception in thread "main" java.lang.NoClassDefFoundError: GraphWalker/NodeEntry
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getMethod0(Class.java:2774)
at java.lang.Class.getMethod(Class.java:1663)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: GraphWalker.NodeEntry
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more
from looking around I find a few answers for this, primarily that the classes aren't on the classpath. Thing is I have all these files in the same folder, and my understanding is the current folder is always on the classpath.
here's abbreviated copies of the code:
testHarness:
import java.util.*;
import GraphWalker.*;
public class testHarness {
public static void main (String args[]) {
new testHarness();
}
public testHarness() {
GraphWalker.UndirectedGraph graph = new GraphWalker.UndirectedGraph(3);
// System.out.println(graph.containsNode(1));
graph.addNode(1);
graph.addNode(2);
graph.addNode(3);
UndirectedGraph:
package GraphWalker;
import java.util.*;
public class UndirectedGraph {
/*
* Based in part on UndirectedGraph.java by Keith Schwarz (htiek#cs.stanford.edu)
*/
public HashMap graphMap;
public UndirectedGraph(int numNodes) {
this.graphMap = new HashMap(numNodes);
}
public void addNode (Integer nodeNum) {
graphMap.put(nodeNum, new NodeEntry(1.0f,0.0f));
}
NodeEntry:
package GraphWalker;
import java.util.*;
public class NodeEntry {
// four inherent values
// credit is the current credit of the node
// nextCredit holds the credit for the next step
// adjList holds a list of adjacent node IDs
// degree holds the number of neighbors
public Float credit;
public Float nextCredit;
public ArrayList adjList;
public Integer degree;
public NodeEntry(Float credit, Float nextCredit) {
this.credit = credit;
this.nextCredit = nextCredit;
this.adjList = new ArrayList();
this.degree = 0;
}
public void addEdge(Integer neighbor) {
this.adjList.add(neighbor);
this.degree += 1;
}
each class has quite a bit more code but I don't think it's relevant to the issue. I'm working on Ubuntu 12.04 and trying to compile and run from both command line and using Geany (simple IDE) same behavior either way.
Any help?
Alrighty,
The issue was that the package files needed to be in a separate folder (named for the package, in my case GraphWalker). I'm not entirely clear on why it compiled fine but at runtime when it went to look for the package it seems to have expected/required them to be in their own folder.
I wouldn't consider that a class path issue, per se, since the files being looked for were in a folder that was on the classpath, just not the folder they needed to be in.

Categories