I have a problem while trying to add a button on an HBox. The error that I got is "Cannot invoke "javafx.scene.layout.HBox.getChildren()" because "this.buttonBox" is null" even though I already have an HBox with fx:id buttonBox. Can someone help me with this?
And I also tried to add a new HBox on the code and then add a button but the button did not show up.
Here is my code:
package com.example.simplemaps;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.util.ArrayList;
public class View {
public static final String INTERFACE_LOCATION = "maps-view.fxml";
private static final Image IMG_BACKGROUND = new Image("com/example/simplemaps/AisleForward.jpg");
private static final Image IMG_FOREGROUND = new Image("com/example/simplemaps/Bunny.png");
//private Controller controller;
#FXML private Label label;
#FXML private ImageView imageBackground;
#FXML private ImageView imageForeground;
#FXML private HBox buttonBox;
public View() {
//controller = new Controller();
}
public void pickUp()
{
// TO DO
}
public void putDown()
{
imageForeground.setImage(IMG_FOREGROUND);
}
public void start()
{
try
{
FXMLLoader fxmlLoader = new FXMLLoader(SimpleMaps.class.getResource(INTERFACE_LOCATION));
Parent anchorPane = fxmlLoader.load();
SimpleMaps.mainStage.setScene(new Scene(anchorPane));
SimpleMaps.mainStage.show();
}
catch(IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void addWhereToButtons(String exit) {
//for(String exit : exits) {
Button button = new Button(exit);
HBox.setMargin(button, new Insets(10.0,0.0,10.0,5.0));
buttonBox.getChildren().add(button);
button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
//controller.selectExitDirection(exit);
}
}
);
//}
}
}
This is the error:
/Library/Java/JavaVirtualMachines/openjdk.jdk/Contents/Home/bin/java --module-path /Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib --add-modules javafx.controls,javafx.fxml -Djava.library.path=/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=51875:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/ulfianidian/Desktop/IPPO/SimpleMaps/target/classes:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx-swt.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.web.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.base.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.fxml.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.media.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.swing.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.controls.jar:/Users/ulfianidian/Desktop/IPPO/javafx-sdk-17.0.0.1/lib/javafx.graphics.jar com.example.simplemaps.SimpleMaps
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
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: Cannot invoke "javafx.scene.layout.HBox.getChildren()" because "this.buttonBox" is null
at com.example.simplemaps.View.addWhereToButtons(View.java:66)
at com.example.simplemaps.Controller.start(Controller.java:21)
at com.example.simplemaps.SimpleMaps.start(SimpleMaps.java:20)
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)
Exception running application com.example.simplemaps.SimpleMaps
Process finished with exit code 1
You need to cast a new HBox to buttonBox, as such.
HBox buttonBox = new HBox();
Related
I wanted to do a test drive on JavaFx, and tried to create an app that can divide two values, but whenever i run it, it gives TextField output to be "".
Here's my code:
package com.example.javafxprojecttest;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import static java.lang.System.*;
public class Divide extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Divide values");
Label divisionVal1 = new Label("Dividend : ");
TextField dividend = new TextField();
TextField divisor = new TextField();
Label divisionVal2 = new Label("Divisor : ");
Button divide = new Button("Divide");
String dividendString = dividend.getText();
String divisorString = divisor.getText();
double d = Double.parseDouble(dividendString) / Double.parseDouble(divisorString);
divide.setOnAction(e -> {
out.println(d);
}
);
GridPane root = new GridPane();
root.addRow(0, divisionVal1, dividend);
root.addRow(1, divisionVal2, divisor);
root.addRow(2, divide);
Scene scene = new Scene(root, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output :
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
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.NumberFormatException: empty String
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:651)
at com.example.javafxprojecttest/com.example.javafxprojecttest.Add.start(Add.java:24)
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
Exception running application com.example.javafxprojecttest.Add
Process finished with exit code 1
I dont know how to fix this nor do I know wht I have to add with this question for you to be able to answer it.
I tried to look at a lot of other questions here on StackOverflow but found none to be useful to me, and I am also rather new to StackOverflow(asking questions), so I dont know much on documenting the error.
Well i got it myself by just transferring all that to inside the button action.
public void start(Stage stage) throws Exception {
stage.setTitle("Divide values");
Label divisionVal1 = new Label("Dividend : ");
TextField dividend = new TextField();
TextField divisor = new TextField();
Label divisionVal2 = new Label("Divisor : ");
Button divide = new Button("Divide");
divide.setOnAction(e -> {
String dividendString = dividend.getText();
String divisorString = divisor.getText();
double d = Double.parseDouble(dividendString) / Double.parseDouble(divisorString);
out.println(d);
}
);
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java: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: Children: child node is null: parent = VBox#4b0d9981
at javafx.graphics/javafx.scene.Parent$3.onProposedChange(Parent.java:542)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.addAll(VetoableListDecorator.java:234)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.addAll(VetoableListDecorator.java:103)
at javafx.graphics/javafx.scene.layout.VBox.<init>(VBox.java:251)
at MultiplyApp.start(MultiplyApp.java:34)
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 MultiplyApp
My code is
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javax.swing.*;
public class MultiplyApp extends Application {
private TextArea firstInt;
private TextArea secondInt;
private TextArea resultLabel;
RecursiveMultiply myObj= new RecursiveMultiply();
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryStage.setTitle("Recursive Multiply App");
Label promptLabel= new Label("Enter first positive integer: ");
Label promptLabel2 = new Label("Enter second positive integer: ");
firstInt= new TextArea();
firstInt.setPrefColumnCount(4);
firstInt.setPrefRowCount(2);
secondInt= new TextArea();
secondInt.setPrefColumnCount(4);
secondInt.setPrefRowCount(2);
Button calcButton = new Button("Ok");
HBox hbox= new HBox(10, promptLabel, firstInt, promptLabel2, secondInt);
VBox vbox= new VBox(10, hbox, resultLabel);
Scene initial= new Scene(vbox);
primaryStage.setScene(initial);
primaryStage.show();
calcButton.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
try {
int Gal = Integer.parseInt(firstInt.getText());
int Mil = Integer.parseInt(secondInt.getText());
if ((Gal <= 0) || (Mil <= 0))
throw new NegativeDoubleException();
int result= myObj.recMul(Gal, Mil);
// Display the results.
resultLabel.setText(String.format(result+" is the product"));
}
catch(NumberFormatException | NegativeDoubleException e) {
JOptionPane.showMessageDialog(null,e.getMessage()); //what happens if you dont enter a number
}
}
});
}
}
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.
Problem:
everything was working fine until I decided to add the media with the mediaPlayer into the program. The reason I know the mediaPlayer is the culprit is because I set the function that runs the mediaPlayer to the end of the main function and the screen would then appear for second and then vanish as oppose to not running at all if I set the function anywhere else.
Relevant code that is causing the problem
private void playThemeIntro()
{
Media gameIntroTheme = new Media("GameIntroTheme.MP3");
mediaPlayer = new MediaPlayer(gameIntroTheme);
mediaPlayer.setAutoPlay(true);
}
Entire code
package whowantstobeamillionairetriviagame;
import java.io.File;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class WhoWantsToBeAMillionaireTriviaGame extends Application
{
private VBox menuLayout;
private MediaPlayer mediaPlayer;
#Override
public void start(Stage startingStage) throws Exception
{
StackPane backgroundSettings = new StackPane();
Image backgroundColor = new Image("http://1.bp.blogspot.com/-p0s06MBIx_U/T8zKIBZ24pI/AAAAAAAAA7Y/n8hMZfpRic0/s1600/dark+blue+wallpaper+10.jpg");
ImageView background = new ImageView();
background.setImage(backgroundColor);
createMenuLayout();
backgroundSettings.getChildren().addAll(background, menuLayout);
playThemeIntro(); // If you comment this out, the program works properly
Scene backgroundScene = new Scene(backgroundSettings);
startingStage.setScene(backgroundScene);
startingStage.setTitle("Who Wants to be a Millionaire");
startingStage.show();
}
private void playThemeIntro()
{
Media gameIntroTheme = new Media("GameIntroTheme.MP3");
mediaPlayer = new MediaPlayer(gameIntroTheme);
mediaPlayer.setAutoPlay(true);
}
private VBox createMenuLayout()
{
menuLayout = new VBox();
menuLayout.setSpacing(20);
menuLayout.setAlignment(Pos.TOP_CENTER);
Image millionaireLogo = new Image(new File("MillionaireLogo1.PNG").toURI().toString());
ImageView logoPicture = new ImageView();
logoPicture.setImage(millionaireLogo);
logoPicture.setPreserveRatio(true);
logoPicture.setSmooth(true);
logoPicture.setCache(true);
menuLayout.getChildren().add(logoPicture);
Button menuButtons[] = new Button[]
{
new Button("Play"),
new Button("Options"),
new Button("Help"),
new Button("Exit")
};
for (int i = 0; i < 4; i++)
{
menuButtons[i].setPrefSize(200, 30);
Rectangle r = new Rectangle(200, 30, Paint.valueOf("346699"));
r.setArcHeight(30);
r.setArcWidth(30);
menuButtons[i].setOnMouseEntered(e -> r.setFill(Paint.valueOf("0f69b4")));
menuButtons[i].setOnMouseExited(e -> r.setFill(Paint.valueOf("346699")));
menuButtons[i].setBackground(Background.EMPTY);
menuButtons[i].setTextFill(Paint.valueOf("White"));
menuButtons[i].setFont(Font.font("Serif", FontWeight.BOLD, 16));
VBox.setMargin(menuButtons[i], new Insets(0, 0, 0, 8));
VBox.setVgrow(menuButtons[i], Priority.ALWAYS);
StackPane sp = new StackPane();
sp.getChildren().addAll(r, menuButtons[i]);
menuLayout.getChildren().add(sp);
}
return menuLayout;
}
public static void main(String[] args)
{
launch(args);
}
}
Error that I got
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$50/1642360923.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'GameIntroTheme.MP3'
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:211)
at javafx.scene.media.Media.<init>(Media.java:391)
at whowantstobeamillionairetriviagame.WhoWantsToBeAMillionaireTriviaGame.playThemeIntro(WhoWantsToBeAMillionaireTriviaGame.java:57)
at whowantstobeamillionairetriviagame.WhoWantsToBeAMillionaireTriviaGame.start(WhoWantsToBeAMillionaireTriviaGame.java:46)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/792965399.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/355629945.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/266742917.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$47/1915503092.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$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/1963387170.run(Unknown Source)
... 1 more
Exception running application whowantstobeamillionairetriviagame.WhoWantsToBeAMillionaireTriviaGame
Java Result: 1
The Media constructor requires a string that represents a URL with a file:, http:, or jar: scheme.
I don't know your project layout, so I can't give a definitive answer, but you probably need something like
Media gameIntroTheme =
new Media(getClass().getResource("GameIntroTheme.MP3").toExternalForm());
Here is the answer
Media gameIntroTheme = new Media(newFile("GameIntroTheme.MP3").toURI().toString());
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();
}
}