This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a basic game in which a dot is moved randomly around the screen, and when it is clicked, the user gets some points. When I run the program, I get a NullPointerException at the start method. I am wondering what I am doing wrong as well as any types for improving the program. Thank you!
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class CatchTheDot extends Application{
//create ball for game
public static Circle dot;
//create pane to run game
public static Pane window;
//create score counter
int score = 0;
//creat random
Random random = new Random();
#Override
public void start(Stage primaryStage) throws Exception {
window.getChildren().add(dot);
// create scene and place on pane
Scene s = new Scene(window, 800, 800);
primaryStage.setTitle("Catch The Dot");
primaryStage.setScene(s);
primaryStage.show();
//move dot
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run(){
window.getChildren().remove(dot);
int ranX = random.nextInt(800-1); // random value from 0 to width
int ranY = random.nextInt(800-1); // random value from 0 to height
window.getChildren().add(ranY, dot);
}
}, 0, 5000);
// create listener
dot.setOnMouseClicked(new EventHandler<MouseEvent>()
{
public void handle(MouseEvent e){
if(e.getSource()==dot)
{
score = score + 10;
if(score == 50)
{
popUp(primaryStage);
}
}
}
});
}
public void popUp(final Stage primaryStage)
{
primaryStage.setTitle("You won!");
final Popup popup = new Popup();
popup.setX(300);
popup.setY(200);
Text t = new Text("You won! Nice job!");
Text tt = new Text("Play again?");
Button yes = new Button("yes");
Button no = new Button("no");
popup.getContent().addAll(t, tt, yes, no);
yes.setOnAction(e -> Yes());
no.setOnAction(e -> No());
}
public void Yes()
{
restartGame();
}
public void No()
{
System.exit(0);
}
public void restartGame()
{
score = 0;
}
public static void main(String[] args)
{
launch(args);
}
}
Error log:
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$156(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at CatchTheDot.start(CatchTheDot.java:34)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application CatchTheDot
Window and Dot have been declared but not defined
In line 34, as the trace says:
window.getChildren().add(dot);
either window or dot (or both) are not initialized by then. Hence the null pointer exception.
Related
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 2 years ago.
I just started to learn Javafx so as a first program, i wanted to code a Media Player and i found a sample at oracle.com. The Project has two java files : MediaControl.java and EmbeddedMediaPlayer.java where the main method is. When i ran the code as copied it worked.
package embeddedmediaplayer;
import java.io.File;
import java.net.URI;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class EmbeddedMediaPlayer extends Application {
private static final String MEDIA_URL =
"http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Embedded Media Player");
Group root = new Group();
Scene scene = new Scene(root, 540, 241);
// create media player
Media media = new Media (MEDIA_URL);
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
MediaControl mediaControl = new MediaControl(mediaPlayer);
scene.setRoot(mediaControl);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
But when i replace the lines which provide the default video (just after the declaration of the class EmbeddedMediaPlayer) by :
File f = new File("test.mp4");
URI u = f.toURI();
private static final String MEDIA_URL = "u";
i get these errors :
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:498)
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:498)
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$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'u'
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:211)
at javafx.scene.media.Media.<init>(Media.java:393)
at embeddedmediaplayer.EmbeddedMediaPlayer.start(EmbeddedMediaPlayer.java:35)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application embeddedmediaplayer.EmbeddedMediaPlayer
Java Result: 1
So, why did i get this? And how can i correctly add the file "test.mp4"?
Use this code
public class VideoPlayer {
public static void main(String[] args) throws InterruptedException {
String fileName = "saved.mp4";
VideoPlayer videoPlayer = new VideoPlayer();
videoPlayer.play(fileName);
}
private void play(String sourceUrl) throws InterruptedException {
final MyVideoFrame frame = new MyVideoFrame();
frame.setSize(new Dimension(500, 500));
IMediaReader reader = ToolFactory.makeReader(sourceUrl);
reader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
MediaListenerAdapter adapter = new MediaListenerAdapter()
{
#Override
public void onVideoPicture(IVideoPictureEvent event)
{
frame.setImage(event.getImage());
}
};
reader.addListener(adapter);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack();
frame.setVisible(true);
while (reader.readPacket() == null)
do {
Thread.sleep(100);
} while(false);
}
private class MyVideoFrame extends JFrame{
public MyVideoFrame() throws HeadlessException {
//setSize(500, 500);
}
Image image;
public void setImage(final Image image) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyVideoFrame.this.image = image;
repaint();
}
});
}
#Override
public synchronized void paint(Graphics g) {
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
}
}
Import xuggle-xuggler-5.4.jar from maven
I have just started with JavaFX. I'm in the process of developing a GUI for my program, and I've used SceneBuilder to design my GUI. I currently have a main class that uses an FXMLLoader to load an .fxml file and displays it. This FXML file has another class called "Controller" as controller. As I said, I haven't had that much to do with JavaFX, so it's possible that I'm just doing it wrong.
Now I have 2 problems: First, I want to communicate between the two classes (code follows). Second, I would like to know how to integrate the code from the main class of the GUI into my already existing main class, I already tried it, but I always got only error messages (stacktrace and code follows).
isi_ko
My GUI Main Class
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Parent normalParent = FXMLLoader.load(getClass().getResource("normalLayout.fxml"));
primaryStage.setTitle("Test");
primaryStage.setScene(new Scene(normalParent, primaryStage.getWidth(), primaryStage.getHeight()));
primaryStage.show();
}
}
My GUI Controller Class
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class Controller implements EventHandler<ActionEvent> {
#FXML Label activePercent;
#FXML Label activeLabel;
#FXML Label activeNumber;
#FXML Label lastLable;
#FXML Label lastNumber;
#FXML Label nextLabel;
#FXML Label nextNumber;
#FXML Label faderValue1;
#FXML Label faderValue2;
#FXML Label faderValue3;
#FXML Label faderValue4;
#FXML Label faderValue5;
#FXML
public void test() {
}
#Override
public void handle(ActionEvent event) {
getFaderValueLable(1).setText("1");
getFaderValueLable(2).setText("2");
getFaderValueLable(3).setText("3");
getFaderValueLable(4).setText("4");
getFaderValueLable(5).setText("5");
}
public Label getFaderValueLable(int i){
switch (i){
case 1:
return faderValue1;
case 2:
return faderValue2;
case 3:
return faderValue3;
case 4:
return faderValue4;
case 5:
return faderValue5;
default:
return null;
}
}
}
My normal Main Class (without GUI Code)
import com.fazecast.jSerialComm.SerialPort;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class Main{
Fader[] faders;
final int baudRate = 1000000; //The Speed that is Used to Communicate with the Arduino
private int physicalFaderAmount; //Amount of Physical Faders, counted from 1
private int faderPages; //Amount of Faderpages, counted from 1
private int activeFaderpage; //The Currently active "physical" Faderpage
private ArduinoController arduinoController; //The Class that communicates with the Arduino
private EosOscController oscController; //The Class that Communicates with Eos
Main(String[] args) {
//Todo Redo this part when UI done
//at the Moment here are just some default values
activeFaderpage = 0;
physicalFaderAmount = 5;
faderPages = 4;
faders = new Fader[physicalFaderAmount];
for (int i = 0; i < physicalFaderAmount; i++){
faders[i] = new Fader(faderPages, i);
}
oscController = new EosOscController(8001, 8000, "192.168.178.133", this);
arduinoController = new ArduinoController(SerialPort.getCommPort("COM4"), this);
}
public static void main(String[] args) {
Main main = new Main(args);
}
// This Class is for Storing Information about a particular physical Fader
public class Fader {
public int[][] values;
// The last 3 Falues the Fader has on the Different Faderpages.
// The First Koordinate is for the Page, the second coordinate is for which of the last 3 Values you want to use.
// The First Value of Every page is the Current value of the Fader
// The Others are for detecting inconsistent Potivalues
public int faderID; //The number of the Physical Fader, starting from 0.
// Uses local values, not OSC
// Sets the Value of the Fader
// Can send the new Value directly to the Arduino or Eos
public void setValue(int physicalPage, int value, boolean sendToEos, boolean sendToArduino) {
if (value != this.values[physicalPage][2] || (Math.max(values[physicalPage][1], value) - Math.min(values[physicalPage][1], value)) > 1) {
values[physicalPage][0] = value;
//Todo: Test this
if (sendToEos) {
oscController.setFaderIntensity(physicalPage, faderID, value / 100.0D, true);
}
//Todo Test this
if (sendToArduino) {
arduinoController.sendMessage(new ArduinoController.MessageToArduino(faderID, value), true);
}
}
values[physicalPage][2] = values[physicalPage][1];
values[physicalPage][1] = value;
}
Fader(int pages, int faderID) {
values = new int[pages][3];
this.faderID = faderID;
}
}
}
My normal Main Class (with GUI Code)
import com.fazecast.jSerialComm.SerialPort;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application{
Fader[] faders;
final int baudRate = 1000000; //The Speed that is Used to Communicate with the Arduino
private int physicalFaderAmount; //Amount of Physical Faders, counted from 1
private int faderPages; //Amount of Faderpages, counted from 1
private int activeFaderpage; //The Currently active "physical" Faderpage
private ArduinoController arduinoController; //The Class that communicates with the Arduino
private EosOscController oscController; //The Class that Communicates with Eos
Main() {
//Todo Redo this part when UI done
//at the Moment here are just some default values
activeFaderpage = 0;
physicalFaderAmount = 5;
faderPages = 4;
faders = new Fader[physicalFaderAmount];
for (int i = 0; i < physicalFaderAmount; i++){
faders[i] = new Fader(faderPages, i);
}
oscController = new EosOscController(8001, 8000, "192.168.178.133", this);
arduinoController = new ArduinoController(SerialPort.getCommPort("COM4"), this); // For PC
// arduinoController = new ArduinoController(SerialPort.getCommPort("ttyACM0"), this); //For Raspberry Pi
}
public static void main(String[] args) {
launch();
}
#Override
public void start(Stage primaryStage) throws Exception {
Parent normalParent = FXMLLoader.load(getClass().getResource("normalLayout.fxml"));
primaryStage.setTitle("Test");
primaryStage.setScene(new Scene(normalParent, primaryStage.getWidth(), primaryStage.getHeight()));
primaryStage.show();
}
// This Class is for Storing Information about a particular physical Fader
public class Fader {
public int[][] values;
// The last 3 Falues the Fader has on the Different Faderpages.
// The First Koordinate is for the Page, the second coordinate is for which of the last 3 Values you want to use.
// The First Value of Every page is the Current value of the Fader
// The Others are for detecting inconsistant Potivalues
public int faderID; //The number of the Physical Fader, starting from 0.
// Uses local values, not OSC
// Sets the Value of the Fader
// Can send the new Value directly to the Arduino or Eos
public void setValue(int physicalPage, int value, boolean sendToEos, boolean sendToArduino) {
if (value != this.values[physicalPage][2] || (Math.max(values[physicalPage][1], value) - Math.min(values[physicalPage][1], value)) > 1) {
values[physicalPage][0] = value;
//Todo: Test this
if (sendToEos) {
oscController.setFaderIntensity(physicalPage, faderID, value / 100.0D, true);
}
//Todo Test this
if (sendToArduino) {
arduinoController.sendMessage(new ArduinoController.MessageToArduino(faderID, value), true);
}
}
values[physicalPage][2] = values[physicalPage][1];
values[physicalPage][1] = value;
}
Fader(int pages, int faderID) {
values = new int[pages][3];
this.faderID = faderID;
}
}
}
Stacktrace for Main Class with GUI Code
Exception in Application constructor
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:498)
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:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class Main
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NoSuchMethodException: Main.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$7(LauncherImpl.java:818)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(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$3(WinApplication.java:177)
... 1 more
Exception running application Main
Process finished with exit code 1
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I don't know if this helps but if I run this code in which i have commented out the setText lines it returns "pointer ok" which suggests that the extCon.setStartValues is pointing to the correct method, although as you pointed out this is another instance of the from and not the one I actually want to populate.
package extrusion;
//import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class ExtrusionController {
private double weight = 16.0;
private double rpm = 30.0;
private double time = 0.5;
#FXML
private TextField timeSecs;
#FXML
private TextField revsPerMin;
#FXML
private TextField sampleWeight;
// #FXML
// void 838383(ActionEvent event) {
//
// }
#FXML
public void setStartValues(){
System.out.println("pointer ok");
// sampleWeight.setText("" + weight);
// revsPerMin.setText("" + rpm);
// timeSecs.setText("" + time);
}
}
package extrusion;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class ExtrusionApp extends Application {
private AnchorPane extrusionForm;
private ExtrusionController extrusionController;
public void start(Stage primaryStage) {
ExtrusionController extCon = new ExtrusionController();
primaryStage.setTitle("ColorMatrix Extrusion");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("ExtrusionForm.fxml"));
try {
extrusionForm = loader.load();
extrusionController = loader.getController();
extCon.setStartValues();
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(extrusionForm);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Thanks James. Here's the Class with extCon commented out and replaced in with extrusionController.setStartValues() which is still giving a null pointer exception. However if I run the original code I posted but comment out the three setText statements in the ExtrusionController class I no longer get the null pointer exception and the code seems to run ok, obviously not populating the TextFields however.
package extrusion;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class ExtrusionApp extends Application {
private AnchorPane extrusionForm;
private ExtrusionController extrusionController;
public void start(Stage primaryStage) {
//ExtrusionController extCon = new ExtrusionController();
primaryStage.setTitle("ColorMatrix Extrusion");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("ExtrusionForm.fxml"));
try {
extrusionForm = loader.load();
extrusionController = loader.getController();
extrusionController.setStartValues();
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(extrusionForm);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
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:498)
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:498)
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$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at extrusion.ExtrusionApp.start(ExtrusionApp.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application extrusion.ExtrusionApp
I'm new to Java and I'm really struggling with a null pointer exception to a TextField. I'm trying to populate the TextFields so when the app opens there is already some data in the fields. I know that I'm pointing to the correct method in the ExtrusionController, as I have tried a System.out.println command in the method and it displays ok. I think the problem might be with the references to the TextFields. I've read dozens of forum posts over the last couple of days but I'm going round in circles.
package extrusion;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class ExtrusionApp extends Application {
private AnchorPane extrusionForm;
private ExtrusionController extrusionController;
public void start(Stage primaryStage) {
ExtrusionController extCon = new ExtrusionController();
primaryStage.setTitle("ColorMatrix Extrusion");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("ExtrusionForm.fxml"));
try {
extrusionForm = loader.load();
extrusionController = loader.getController();
extCon.setStartValues();
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(extrusionForm);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
package extrusion;
//import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class ExtrusionController {
private double weight = 16.0;
private double rpm = 30.0;
private double time = 0.5;
#FXML
private TextField timeSecs;
#FXML
private TextField revsPerMin;
#FXML
private TextField sampleWeight;
// #FXML
// void 838383(ActionEvent event) {
//
// }
#FXML
public void setStartValues(){
System.out.println();
sampleWeight.setText("" + weight);
revsPerMin.setText("" + rpm);
timeSecs.setText("" + time);
}
}
extCon and extrusionController contain 2 different controller instances. extrusionController is used when loading the fxml and objects from the fxml are injected to this instance.
However you call the setStartValues method for the extCon instance that is not used with a fxml and therefore contains null values in fields.
While working on trying to make some simple buttons with Event Driven Programming I was looking at an example in my textbook (Intro to Java Programming 10th edi.) I followed some code from the book to try and replicate it myself for a project I'm working on. The program compiles, but when it runs I get:
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class ButtonPackage.ButtonEvent
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodException: ButtonPackage.ButtonEvent.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:818)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(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$149(WinApplication.java:191)
... 1 more
After getting advice from the answers I was able to get it working. Below is the corrected condensed code:
package ButtonPackage;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
/**
* Created by Brandon on 12/5/2015.
*/
public class ButtonEvent extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override //Override start method Application Class
public void start(Stage primaryStage) {
//create pane set properties
HBox pane = new HBox(10);
pane.setAlignment(Pos.CENTER);
Button btEnter = new Button("ENTER NUMBER");
Button btCheck = new Button("CHECK IF WINNER");
EnterNumber handler1 = new EnterNumber();
btEnter.setOnAction(handler1);
CheckWinner handler2 = new CheckWinner();
btCheck.setOnAction(handler2);
pane.getChildren().addAll(btEnter, btCheck);
//Create scene place on stage
Scene scene = new Scene(pane);
primaryStage.setTitle("HandleEvent"); //Set Stage Title
primaryStage.setScene(scene); //Place scene in stage
primaryStage.show(); //Display stage
}//end start
}//end ButtonEvent
class EnterNumber implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent e) {
System.out.println("ENTER NUMBER button clicked");
}//end handle
}//end EnterNumber
class CheckWinner implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent e) {
System.out.println("CHECK IF WINNER button clicked");
//eventLottery.main();
}//end handle
}//end CheckWinner
Thanks for the help!
It looks like you are running this in IntelliJ. While it is permissible for an Application subclass not to have a main(...) method, not all IDEs support this execution mode.
Note that, in any execution mode, your main class must be public.
If you want to run from inside the IDE, add a main method that simply calls launch():
public class ButtonEvent extends Application {
// existing code ...
public static void main(String[] args) {
launch(args);
}
}
(or just run it directly from the command line).
You did not define a public static main(String[] args) method. You need to define this method, and tell java which class this method is in.
I have tried to learn Java FX so I used some of the Oracle Eample Code but when I tried to run it in Netbean IDE, It gives me a Runtime Error. Here is a Piece of code :
public class WebViewTestOne {
private Scene scene;
#Override
public void start(Stage stage) {
stage.setTitle("Web View");
scene = new Scene(new Browser(),750,500, Color.web("#666970"));
stage.setScene(scene);
scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
public static void main(String[] args){
launch(args);
}
}
and this is the Exception.
Exception in thread "main" java.lang.RuntimeException: Error: class webviewtest.one.WebViewTestOne is not a subclass of javafx.application.Application
at javafx.application.Application.launch(Application.java:254)
at webviewtest.one.WebViewTestOne.main(WebViewTestOne.java:33)
Java Result: 1
So what is wrong? I mean since this is an Example from the official Site, why even there is an error? ( the error happens at the launch(args)
EDIT: Ok based on the Answer by rob I added the Extension that I missed from the example, Now it gives even much more exception after I tried to extend the code. below is the new Code and the Log for the exception.
package webviewtest.one;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener.Change;
import javafx.concurrent.Worker.State;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.PopupFeatures;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebHistory.Entry;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class WebViewTestOne extends Application{
private Scene scene;
#Override
public void start(Stage stage) {
// create scene
stage.setTitle("Web View");
scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
stage.setScene(scene);
// apply CSS style
scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
// show stage
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Browser extends Region {
private HBox toolBar;
private static String[] imageFiles = new String[]{
"product.png",
"blog.png",
"documentation.png",
"partners.png",
"help.png"
};
private static String[] captions = new String[]{
"Products",
"Blogs",
"Documentation",
"Partners",
"Help"
};
private static String[] urls = new String[]{
"http://www.oracle.com/products/index.html",
"http://blogs.oracle.com/",
"http://docs.oracle.com/javase/index.html",
"http://www.oracle.com/partners/index.html",
// WebViewSample.class.getResource("help.html").toExternalForm()
};
final ImageView selectedImage = new ImageView();
final Hyperlink[] hpls = new Hyperlink[captions.length];
final Image[] images = new Image[imageFiles.length];
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
final Button showPrevDoc = new Button("Toggle Previous Docs");
final WebView smallView = new WebView();
final ComboBox comboBox = new ComboBox();
private boolean needDocumentationButton = false;
public Browser() {
//apply the styles
getStyleClass().add("browser");
for (int i = 0; i < captions.length; i++) {
// create hyperlinks
Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
Image image = images[i] =
new Image(getClass().getResourceAsStream(imageFiles[i]));
hpl.setGraphic(new ImageView(image));
final String url = urls[i];
final boolean addButton = (hpl.getText().equals("Documentation"));
// process event
hpl.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
needDocumentationButton = addButton;
webEngine.load(url);
}
});
}
comboBox.setPrefWidth(60);
// create the toolbar
toolBar = new HBox();
toolBar.setAlignment(Pos.CENTER);
toolBar.getStyleClass().add("browser-toolbar");
toolBar.getChildren().add(comboBox);
toolBar.getChildren().addAll(hpls);
toolBar.getChildren().add(createSpacer());
//set action for the button
showPrevDoc.setOnAction(new EventHandler() {
#Override
public void handle(Event t) {
webEngine.executeScript("toggleDisplay('PrevRel')");
}
});
smallView.setPrefSize(120, 80);
//handle popup windows
webEngine.setCreatePopupHandler((PopupFeatures config) -> {
smallView.setFontScale(0.8);
if (!toolBar.getChildren().contains(smallView)) {
toolBar.getChildren().add(smallView);
}
return smallView.getEngine();
});
//process history
final WebHistory history = webEngine.getHistory();
history.getEntries().addListener((Change<? extends Entry> c) -> {
c.next();
c.getRemoved().stream().forEach((e) -> {
comboBox.getItems().remove(e.getUrl());
});
c.getAddedSubList().stream().forEach((e) -> {
comboBox.getItems().add(e.getUrl());
});
});
//set the behavior for the history combobox
comboBox.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
int offset =
comboBox.getSelectionModel().getSelectedIndex()
- history.getCurrentIndex();
history.go(offset);
}
});
// process page loading
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
#Override
public void changed(ObservableValue<? extends State> ov,
State oldState, State newState) {
toolBar.getChildren().remove(showPrevDoc);
if (newState == State.SUCCEEDED) {
JSObject win =
(JSObject) webEngine.executeScript("window");
win.setMember("app", new JavaApp());
if (needDocumentationButton) {
toolBar.getChildren().add(showPrevDoc);
}
}
}
}
);
// load the home page
webEngine.load("http://www.oracle.com/products/index.html");
//add components
getChildren().add(toolBar);
getChildren().add(browser);
}
// JavaScript interface object
public class JavaApp {
public void exit() {
Platform.exit();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
double tbHeight = toolBar.prefHeight(w);
layoutInArea(browser,0,0,w,h-tbHeight,0,HPos.CENTER,VPos.CENTER);
layoutInArea(toolBar,0,h-tbHeight,w,tbHeight,0,HPos.CENTER,VPos.CENTER);
}
#Override
protected double computePrefWidth(double height) {
return 750;
}
#Override
protected double computePrefHeight(double width) {
return 600;
}
}
and this is the Exception Log:
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:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:363)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:303)
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:483)
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:875)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(LauncherImpl.java:157)
at com.sun.javafx.application.LauncherImpl$$Lambda$48/128893786.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Input stream must not be null
at javafx.scene.image.Image.validateInputStream(Image.java:1099)
at javafx.scene.image.Image.<init>(Image.java:684)
at webviewtest.one.Browser.<init>(WebViewTestOne.java:104)
at webviewtest.one.WebViewTestOne.start(WebViewTestOne.java:49)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1135703189.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/1051754451.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/135339377.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1775282465.run(Unknown Source)
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$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
... 1 more
Exception running application webviewtest.one.WebViewTestOne
Java Result: 1
You have to extend Application. I believe that is what the error means.
Here is an example from Java FX Site:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class MyApp extends Application
{
public void start(Stage stage)
{
Circle circ = new Circle(40, 40, 30);
Group root = new Group(circ);
Scene scene = new Scene(root, 400, 300);
stage.setTitle("My JavaFX Application");
stage.setScene(scene);
stage.show();
}
}