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
Related
I tried to make a window with an icon with JavaFx but it doesn't work.
I don't know why ? I've been testing with InputStream and I had an error also. I use URL and it doesn't work also. HELP :( please
The Main Class:
package fr.fireblaim.firelauncherlib_test;
import fr.fireblaim.firelauncherlib.WindowOptions;
import fr.fireblaim.firelauncherlib.graphics.Base;
import fr.fireblaim.firelauncherlib.utils.ResourceLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Base {
private WindowOptions windowOptions = new WindowOptions(1280, 720, "Launcher Test", true, StageStyle.UNDECORATED);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Scene scene = new Scene(new LauncherPanel(windowOptions));
setupWindow(stage, scene, windowOptions, ResourceLoader.loadImage("icon.png"));
}
}
The ResourceLoader Class:
package fr.fireblaim.firelauncherlib.utils;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class ResourceLoader {
private static String resourceLocation = "resources/";
public static Image loadImage(String file) {
try {
BufferedImage image = ImageIO.read(new URL( "file:" + getResourceLocation() + file));
return SwingFXUtils.toFXImage(image, null);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void setResourceLocation(String resourceLocation) {
ResourceLoader.resourceLocation = resourceLocation;
}
public static String getResourceLocation() {
return resourceLocation;
}
}
The Base Class:
package fr.fireblaim.firelauncherlib.graphics;
import fr.fireblaim.firelauncherlib.WindowOptions;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.swing.*;
import java.awt.*;
public abstract class Base extends Application {
private Point point = new Point();
public abstract void start(Stage stage) throws Exception;
protected void setupWindow(Stage stage, Scene scene, WindowOptions windowOptions) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
System.err.println("[FireLauncherLib] Can't setup the window:\n" + e);
}
stage.initStyle(windowOptions.getStageStyle());
stage.setResizable(false);
stage.setTitle(windowOptions.getTitle());
stage.setWidth(windowOptions.getWidth());
stage.setHeight(windowOptions.getHeight());
stage.setAlwaysOnTop(true);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
Platform.exit();
System.exit(0);
}
});
if(windowOptions.isMovable()) {
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
point.x = (int)(stage.getX() - event.getScreenX());
point.y = (int)(stage.getY() - event.getScreenY());
}
});
scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
stage.setX(event.getScreenX() + point.x);
stage.setY(event.getScreenY() + point.y);
}
});
}
stage.setScene(scene);
stage.show();
}
protected void setupWindow(Stage stage, Scene scene, WindowOptions windowOptions, Image icon) {
setupWindow(stage, scene, windowOptions);
stage.getIcons().clear();
stage.getIcons().add(icon);
}
}
I have this error :
javax.imageio.IIOException: Can't get input stream from URL!
at javax.imageio.ImageIO.read(ImageIO.java:1401)
at fr.fireblaim.firelauncherlib.utils.ResourceLoader.loadImage(ResourceLoader.java:17)
at fr.fireblaim.firelauncherlib_test.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
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.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$10(GtkApplication.java:245)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException: resources/icon.png (Aucun fichier ou dossier de ce type)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at java.net.URL.openStream(URL.java:1068)
at javax.imageio.ImageIO.read(ImageIO.java:1399)
... 11 more
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at javafx.stage.Stage$4.onChanged(Stage.java:696)
at com.sun.javafx.collections.TrackableObservableList.lambda$new$0(TrackableObservableList.java:45)
at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:155)
at java.util.AbstractList.add(AbstractList.java:108)
at fr.fireblaim.firelauncherlib.graphics.LauncherBase.setupWindow(LauncherBase.java:70)
at fr.fireblaim.firelauncherlib_test.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
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.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$10(GtkApplication.java:245)
at java.lang.Thread.run(Thread.java:748)
I use Intellij IDEA 2019.3.4 Ultimate
The Resource Structure:
src
resources
icon.png
It seems from your code - as you use the "file:" protocol - that you expect the images to be in a directory on the filesystem. So why not change the call load from File not URL:
File f = new File(getResourceLocation(), file);
ImageIO.read(f)
You can then fix the directory location issue by checking where Java thinks those files are from by calling / printing:
f.getAbsolutePath();
f.exists();
Alternatively if these images are in the same jar as your code you should be using getClass().getResourceAsStream() to locate InputStream to pass to ImageIO.read(is).
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.
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();
}
}
So I've recently started working with JavaFX to try and insert video and audio into my java programs. Audio has worked just fine, but for some reason every time I try and play a video file, it returns a MEDIA_UNSUPPORTED exception. I've read around and saw that the video file needed to be MP4 (which it is), so I tried converting it to a different type then re-converting it to MP4 (H.264 & AAC) with a few different converters and nothing changes.
Here's the code I'm working with:
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
public class CallVideo extends JFrame{
public static final String VID_URL = "file:/C:/Users/Public/Videos/Videos/testCon.mp4"; //http://static.clipcanvas.com/sample/clipcanvas_14348_H264_320x180.mp4
private JFXPanel panel;
public CallVideo(String url)
{
panel = new JFXPanel();
Platform.runLater(new Runnable()
{
public void run()
{
final Media clip = new Media(VID_URL);
final MediaPlayer player = new MediaPlayer(clip);
final MediaView viewer = new MediaView(player);
viewer.setFitHeight(200);
viewer.setFitWidth(200);
final Button button = new Button("Bing Zzzzt!");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event)
{
viewer.getMediaPlayer().seek(Duration.ZERO);
viewer.getMediaPlayer().play();
}
});
setMediaEventHandlers(viewer);
VBox vid = new VBox();
vid.getChildren().addAll(viewer, button);
Scene aScene = new Scene(vid, 200, 200);
panel.setScene(aScene);
}
});
this.add(panel);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
private void setMediaEventHandlers(final MediaView view) {
final MediaPlayer player = view.getMediaPlayer();
System.out.println("Initial: " + player.getStatus());
player.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
#Override
public void changed(ObservableValue<? extends MediaPlayer.Status> observable, MediaPlayer.Status oldStatus, MediaPlayer.Status curStatus) {
System.out.println("Current: " + curStatus);
}
});
if (player.getError() != null) {
System.out.println("Initial Error: " + player.getError());
}
player.setOnError(new Runnable() {
#Override public void run() {
System.out.println("Current Error: " + player.getError());
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CallVideo(VID_URL);
}
});
}
}
The error occurs on the line where the "Media" object is initialized (beginning of constructor).
I'm at a total loss to see what the problem is. I've seen questions about the audio playing but the video not showing up, but it doesn't even do that for me...
In case someone needs it:
Eclipse
JDK 7
JavaFX 2.0
Windows 7 Pro
EDIT:
First off, I noticed I'm actually using JavaFX 2.0... Might that be the problem?
I've tested both versions provided in the answer, and both return this error (called by the statusListener) when using the URL provided by that answer:
Current Error: MediaException: MEDIA_UNSUPPORTED : com.sun.media.jfxmedia.MediaException: "Error enter code herelocator unsupported media format" : com.sun.media.jfxmedia.MediaException: "Error locator unsupported media format"
When using my own file, the program returns this error immediately upon calling the Media constructor, as before:
Exception in thread "AWT-EventQueue-0" MediaException: MEDIA_UNSUPPORTED : Unrecognized file signature!
at javafx.scene.media.Media.<init>(Media.java:382)
at CallVideo.<init>(CallVideo.java:27)
at CallVideo$5.run(CallVideo.java:90)
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$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$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)
I've updated the code I'm using above.
SOLVED!
The reason is really I was using an inappropriate JavaFX (and possibly JDK) for the job. I'm not really in control of that stuff since these are school computers, but that messed me up something good... Thanks for the help! I updated it with my final code.
This worked for me after I modified your program a little bit to fix a couple of issues.
Some changes I applied:
A MediaView is necessary to view the video, so one needs to be created and added to an active JavaFX scene in order for the video to be seen.
Some JavaFX controls need to be created on the JavaFX application thread rather than the main thread, otherwise you get java.lang.IllegalStateException: Toolkit not initialized.
Monitoring media error events and adding some diagnostic logs helps troubleshoot media encoding issues.
A JavaFX only solution
Your program embeds JavaFX in a Swing application which is a bit more complex then just playing Media in a standard JavaFX application. Corresponding code for playback of an mp4 in a standard JavaFX application is supplied in my answer to: Can't play mp4 converted file - JavaFX 2.1. Using just JavaFX is recommended unless you have a specific need for Swing (such as embedding your JavaFX based media player inside an existing large Swing application).
Oracle provide a good tutorial for Incorporating Media Assets Into JavaFX Applications.
The JavaFX media package description documents the media playback encodings, containers and protocols which JavaFX supports.
Sample for playing back mp4 video from a Swing App using a JavaFX MediaPlayer
Note the sample only catches a subset of the possible media errors. For a code template which can catch and log all media errors see the JavaFX media error handling documentation.
import javax.swing.*;
import javafx.application.Platform;
import javafx.beans.value.*;
import javafx.embed.swing.JFXPanel;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.media.*;
import javafx.util.Duration;
public class VideoPlayer extends JFrame {
public static final String VID_URL =
"http://static.clipcanvas.com/sample/clipcanvas_14348_H264_320x180.mp4";
private static final int VID_WIDTH = 320;
private static final int VID_HEIGHT = 180;
private static final int PLAYER_WIDTH = 320;
private static final int PLAYER_HEIGHT = 265;
private void play(final String url) {
final JFXPanel panel = new JFXPanel();
Platform.runLater(new Runnable() {
#Override public void run() {
initFX(panel, url);
}
});
this.add(panel);
this.setSize(PLAYER_WIDTH, PLAYER_HEIGHT);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
private void initFX(JFXPanel panel, String url) {
MediaView mediaView = createMediaView(url);
final Scene playerScene = new Scene(
createPlayerLayout(mediaView),
PLAYER_WIDTH,
PLAYER_HEIGHT
);
setMediaEventHandlers(
mediaView
);
panel.setScene(playerScene);
}
private MediaView createMediaView(String url) {
final Media clip = new Media(url);
final MediaPlayer player = new MediaPlayer(clip);
final MediaView view = new MediaView(player);
view.setFitWidth(VID_WIDTH);
view.setFitHeight(VID_HEIGHT);
return view;
}
private VBox createPlayerLayout(final MediaView view) {
final Button button = new Button("Play From Start");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
view.getMediaPlayer().seek(Duration.ZERO);
view.getMediaPlayer().play();
}
});
final VBox layout = new VBox(8);
layout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(
view,
button
);
layout.setStyle("-fx-background-color: linear-gradient(to bottom, derive(lightseagreen, -20%), lightseagreen);");
return layout;
}
private void setMediaEventHandlers(final MediaView view) {
final MediaPlayer player = view.getMediaPlayer();
System.out.println("Initial: " + player.getStatus());
player.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
#Override
public void changed(ObservableValue<? extends MediaPlayer.Status> observable, MediaPlayer.Status oldStatus, MediaPlayer.Status curStatus) {
System.out.println("Current: " + curStatus);
}
});
if (player.getError() != null) {
System.out.println("Initial Error: " + player.getError());
}
player.setOnError(new Runnable() {
#Override public void run() {
System.out.println("Current Error: " + player.getError());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
VideoPlayer player = new VideoPlayer();
player.play(VID_URL);
}
});
}
}
SOLVED!
Nice to see that original poster was able to get video playback working and the final error was just using an old JavaFX version (2.0) which does not support mp4 playback. Updating to JavaFX 2.2+ (which does support mp4 playback) fixed the issue.