NullPointerException when using an hexadecimal value as the parameter of a method - java

I'm writing a simple program that consists of a window with 8 buttons with different colors added to a VBox that then is added to the program stage's scene.
For changing a button's color, I have to call the setRippleColor() method, whose definition is the following:
public void setRippleColor(Color color) {
((Shape) ((SkinBase) getSkin()).getChildren().get(0)).setFill(color);
}
The problem is that when I call this method using a Color object as its parameter, I get a NullPointerException.
For example, if I use this code:
buttonGreen.setRippleColor((Color.web("0x259B24")));
buttonOrange.setRippleColor(Color.web("0xe67e22"));
buttonBlue.setRippleColor(Color.web("0x3498db"));
buttonPurple.setRippleColor(Color.web("0x9b59b6"));
buttonYellow.setRippleColor(Color.web("0xf1c40f"));
buttonRed.setRippleColor(Color.web("0xe74c3c"));
buttonBrown.setRippleColor(Color.web("0x663300"));
buttonGrey.setRippleColor(Color.web("0x222222"));
VBox verticalLayout = new VBox(8);
verticalLayout.getChildren().addAll(buttonGreen,
buttonOrange,
buttonBlue,
buttonPurple,
buttonYellow,
buttonRed,
buttonBrown,
buttonGrey);
the console is going to say this:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at CustomButton.setRippleColor(CustomButton.java:166)
at StartingPoint.start(StartingPoint.java:25)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
Being the 166th and 25th lines of code the definition of the method and the first call thereof, respectively.
Nevertheless, if instead of using an hexadecimal value as a color I use one of the default colors of the Color class (Color.GREEN, for example), everything runs perfectly.
It's important to mention that I'm not using the java.awt.Color class instead of javafx.scene.paint.Color; the library is no the problem.
UPDATE: I did some rudamentary logging in order to know what's null.
Instead of using Color.web("...") as a parameter for setRippleColor(), I created a few Color objects whose definition is what at the beggining was the setRippleColor()'s parameter, and I surrounded the calls to the setRippleMethod() with the following try{} catch{}:
Color green = Color.web("0x259B24");
try {
buttonGreen.setRippleColor(green);
} catch (NullPointerException exception) {
SkinBase skin = (SkinBase) buttonGreen.getSkin();
ObservableList<Node> children = skin.getChildren();
Shape shape = (Shape) skin.getChildren().get(0);
System.out.println("Color " + green);
System.out.println("Skin: " + skin);
System.out.println("Children: " + children);
System.out.println("Shape: " + shape);
}
And this is what the console prints out:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at StartingPoint.start(StartingPoint.java:31)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
For as far as I understand, this means that the button's skin's children return null, but I don't understand why does this not happen when I use Color.GREEN instead of the Color object found in the above code.
UPDATE 2: It turns out that when I use Color.GREEN as a parameter for setRippleColor() the result is the same that if I use Color.web("#colorstring"), thing that is obvious and there wouldn't be an explanation if that wasn't the case. I don't know why, but I have the memory of using Color.GREEN and having the program running without any errors.
The good thing is that now I will remember that every time that something doesn't make sense, I have to run the code again and make sure that it doesn't make sense to me because I don't have enough knowledge about the topic, and not because it never happened.
So, the problem was due to that the button's skin hasn't been initialized before the setRippleColor() method is called.
This is how I solved it:
try{
((Shape) ((SkinBase) getSkin()).getChildren().get(0)).setFill(color);
} catch (NullPointerException exception){
createDefaultSkin();
setRippleColor(color);
}
If the skin hasn't been initialized when the method is called, it's initialized and then the setRippleColor() calls himself again.

The most likely cause is that you are trying to call these methods before the skin has been initialized. In this scenario, getSkin() will return null and thus ((SkinBase)getSkin()).getChildren() will throw a null pointer exception.
A simple way to avoid this is to do a null check:
public void setRippleColor(Color color) {
if (getSkin() == null) {
createDefaultSkin();
}
SkinBase skin = (SkinBase) getSkin();
Shape shape = (Shape) skin.getChildren().get(0);
shape.setFill(color);
}
You can probably vastly improve on this code: it seems you should really know somewhere in the code what the first child of the skin is, and should be able to reference it directly. This will at least provide a fix, though.

Related

java.lang.reflect.InvocationTargetException in javafx program [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am currently trying to code a simple MediaPlayer to explore javafx.
(beginner here)
I want to open a mp3 file and simply play it but when i launch it there is an exception ive never seen.
Heres the code:
#Override
public void start(Stage primaryStage) {
Media pick = new Media("file:///" + System.getProperty("Benutzer.dir").replace('\\', '/') + "/" + "oof.mp3");
MediaPlayer player = new MediaPlayer(pick);
MediaView mediaView = new MediaView(player);
Group root = new Group(mediaView);
Scene scene = new Scene(root, 500, 200);
primaryStage.setTitle("MediaPlayerTest");
primaryStage.setScene(scene);
primaryStage.show();
player.play();
}
public static void main(String[] args) {
launch();
}
And the exception:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at soundEdit.start(soundEdit.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
Already tried to find a solution but cant really find anything.
Thanks for the help.
If you read the stack of error you will notice that the error is caused by a null pointer exception at line 13 of the code can you kindly highlight that line, not sure which one.
Also when getting resources it's best to use the getClass().getResourcesAsStream() or getClass().getResource() methods.

Exception in "JavaFX Application Thread" when using JavaFX control

I am initializing a generic JavaFX 8 ComboBox with Enum values as follows:
ObservableList<MyEnumClass> myValues = FXCollections
.observableArrayList(MyEnumClass.FIRST_ENUM,
MyEnumClass.SECOND_ENUM, MyEnumClass.THIRD_ENUM);
myEnumComboBox = new ComboBox<MyEnumClass>(myValues);
A test application shows the ComboBox with the Enum values as expected and selecting other values also works fine. But one thing puzzels me: Even though I can not observe any apparent malfunction, my Eclipse console nevertheless notifies me about an exception in thread "JavaFX Application Thread" whenever I select a new value from the ComboBox's menu. The exception seems to be related to the native JavaFX code that hides the ComboBox's popup control:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: null source
at java.util.EventObject.<init>(Unknown Source)
at java.awt.AWTEvent.<init>(Unknown Source)
at sun.awt.UngrabEvent.<init>(Unknown Source)
at javafx.embed.swing.SwingNode$10.handle(Unknown Source)
[9 lines omitted]
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at com.sun.javafx.stage.WindowPeerListener.focusUngrab(Unknown Source)
[4 lines omitted]
at com.sun.glass.ui.Window.handleWindowEvent(Unknown Source)
at com.sun.glass.ui.Window.notifyFocusUngrab(Unknown Source)
at com.sun.glass.ui.win.WinWindow._ungrabFocus(Native Method)
at com.sun.glass.ui.Window.ungrabFocus(Unknown Source)
at com.sun.javafx.tk.quantum.WindowStage.ungrabFocus(Unknown Source)
at javafx.stage.Window.decreaseFocusGrabCounter(Unknown Source)
at javafx.stage.PopupWindow.handleAutohideActivation(Unknown Source)
at javafx.stage.PopupWindow.impl_visibleChanged(Unknown Source)
at javafx.stage.Window$9.invalidated(Unknown Source)
at javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.BooleanPropertyBase.set(Unknown Source)
at javafx.stage.Window.setShowing(Unknown Source)
at javafx.stage.Window.hide(Unknown Source)
at javafx.stage.PopupWindow.hide(Unknown Source)
at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.hide(Unknown Source)
[44 lines omitted]
at java.lang.Thread.run(Unknown Source)
Can somebody explain what exactly is happening here and what I can or should do about it?
EDIT - The exception was caused by a leftover SwingNode from some earlier experiment on the same Pane as the ComboBox. Deleting the SwingNode made the exception vanish.

GWT Maps Icon.NewInstance intermittently throwing exception

I'm creating a custom icon to use as a marker on a map, and intermittently, but quite often this function:
private Icon createIcon(String Url) {
Icon icon = Icon.newInstance(Url); //<-- This line throws exception
icon.setIconSize(Size.newInstance(30, 30));
icon.setIconAnchor(Point.newInstance(6, 20));
icon.setInfoWindowAnchor(Point.newInstance(14, 4));
return icon;
}
throws this exception:
11:05:55.076 [ERROR] [simplemap] Uncaught exception escaped
com.google.gwt.core.client.JavaScriptException: (TypeError) #com.google.gwt.core.client.impl.Impl::apply(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)([JavaScript object(311), JavaScript object(310), JavaScript object(333)]): undefined is not a function
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
Does anybody have any insight as to why this happens and what I can do to fix this behavior?
This ended up being a concurrency issue where the map was not finished loading when the icons were trying to be generated. When I moved some code around so it only ran after the Maps asynchronous load was finished this issue went away.

Java Game - ClassCastException

I am developing a simple java game and my scrollbar is raising an exception.
The scrollbar is supposed to be a "gameslider".
Exception in thread "Thread-3" java.lang.ClassCastException: sun.java2d.NullSurfaceData cannot be cast to sun.java2d.d3d.D3DSurfaceData
at sun.java2d.d3d.D3DRenderer.copyArea(Unknown Source)
at sun.java2d.d3d.D3DSurfaceData.copyArea(Unknown Source)
at sun.java2d.SunGraphics2D.doCopyArea(Unknown Source)
at sun.java2d.SunGraphics2D.copyArea(Unknown Source)
at javax.swing.BufferStrategyPaintManager.copyArea(Unknown Source)
at javax.swing.RepaintManager.copyArea(Unknown Source)
at javax.swing.JViewport.blitDoubleBuffered(Unknown Source)
at javax.swing.JViewport.windowBlitPaint(Unknown Source)
at javax.swing.JViewport.setViewPosition(Unknown Source)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.hsbStateChanged(Unknown Source)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.fireStateChanged(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.setRangeProperties(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.setValue(Unknown Source)
at javax.swing.JScrollBar.setValue(Unknown Source)
at GameEnvironment.GamePanel.gameUpdate(GamePanel.java:171)
at GameEnvironment.GamePanel.run(GamePanel.java:73)
at java.lang.Thread.run(Unknown Source)
Code Line is following:
if (reachedMiddle)
scrollPane.getHorizontalScrollBar().setValue(player.getX() - (widthHorizontalScrollBar / 2));
The exception will be raised more or less randomly. I didnt figured it out so far.
I would make sure this code is run on the GUI Event Thread. If you call the Swing components on other threads you can get strange, randonm errors.
Have a look at using SwingUtilities.invokeLater(Runnable) to perform the tasks where the Swing components are updated.

Handle Applet throwing java.lang.ExceptionInInitializerError preventing it from running

We are developing java applet and embedding it in our web pages. When the applet is loaded via HTML APPLET tags, the browser/JVM prompts the user to allow it to run. When we hit cancel, the java console indicates the following exception:
java.lang.RuntimeException: java.lang.ExceptionInInitializerError
at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission getenv.TEMP)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.System.getenv(Unknown Source)
at downLoadApp.<clinit>(downLoadApp.java:15)
... 21 more
Exception: java.lang.RuntimeException: java.lang.ExceptionInInitializerError
Now, I realize it's most likely because the class java tried to load was prevented from loading, and therefore the exception is thrown, but how do we gracefully handle this situation in the browser? I'd like to detect that the applet was denied and post a reasonable response to the condition, but I'm unaware of how to catch this exception since it appears to have been thrown by the JVM in reaction to not getting the jar file to load rather than code written in it...
Ideas?
Thanks!
You can catch the access control exception by putting the call to System.getenv in downLoadApp.java line 15 in a try-catch statement. That is, instead of this:
static String tmp = System.getenv("TEMP");
you should have:
static String tmp;
static {
try {
tmp = System.getenv("TEMP");
} catch (java.security.AccessControlException ace) {
// tmp is not set, maybe use some default value?
}
}
Do you call System.getenv("TEMP") somewhere in the static context of the downLoadApp class? Most probably this is in the initializer of a static field, but it could be in a static code block.
This is the place where it fails (a java.security.AccessControlException is thrown). The rest of the stack trace are errors following from that. You need to catch this exception to detect that you don't have the appropriate permissions.
As you can't catch exceptions of static field initializers, you need to move the call to getenv into a method or a static code block.
I don't think that you can catch this exception as this is thrown by JVM while loading applet.

Categories

Resources