My executable jar file cannot run due to NullPointerException - java

I am trying to pack my project into runable jar file , and i got this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at eBridge.LoginPage.initialize(LoginPage.java:66)
at eBridge.LoginPage.<init>(LoginPage.java:55)
at eBridge.LoginPage.<init>(LoginPage.java:49)
at eBridge.eBridgFrame.<init>(eBridgFrame.java:37)
at eBridge.eBridgFrame$1.run(eBridgFrame.java:24)
at java.awt.event.InvocationEvent.dispatch(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)
My main method is on a class calss eBridgFrame , and itz running base on tabs... here is the eBridgFrame class:
package eBridge;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import javax.swing.WindowConstants;
public class eBridgFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
eBridgFrame thisClass = new eBridgFrame();
thisClass.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
/**
* This is the default constructor
*/
public eBridgFrame() {
super();
initialize();
JPanel panel = new LoginPage(this);
this.getContentPane().add(panel);
this.setVisible(true);
}
/**
* This method initializes this
*
* #return void
*/
private void initialize() {
this.setSize(950, 720);
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.setName("EBRIDG");
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/eBridge/images/eB.png")));
this.setResizable(false);
this.setMinimumSize(new Dimension(950, 720));
this.setPreferredSize(new Dimension(950, 720));
this.setContentPane(getJContentPane());
this.setTitle("EBRIDG");
}
//Pop up msg to confirm closing by overiding javax.swing.JFrame.processWindowEvent() method
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
int exit = JOptionPane.showConfirmDialog(this, "Are you sure?");
if (exit == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
}
/**
* This method initializes jContentPane
*
* #return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
}
return jContentPane;
}
}
Can someone save me ??? Thanks a lot !

It would really have helped if you'd told us which is line 66, but my guess is that it's this:
this.setIconImage(Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/eBridge/images/eB.png")));
It sounds like you just haven't included eB.png in your jar file, or you haven't included it in the right place.

You need to look at below line;
eBridge.LoginPage.initialize(LoginPage.java:66)

Related

How can i read a file in Javafx Project? [duplicate]

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

.setLocation Not Working With A Timer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am creating a 'Troll' like application to use in a YouTube video, and I want a JFrame to jump around the screen every 1/2 second.
Heres my code:
package troll1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class troll extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
troll w1 = new troll();
w1.setVisible(true);
w1.setSize(500,500);
}
public Random ran;
public int random;
public troll w1;
public Timer t;
public troll() {
Timer t = new Timer(500, this);
t.start();
}
#Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
w1.setLocation(random, random);
}
}
}
The problem is, when I run this code, I get a error saying,
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at troll1.troll.actionPerformed(troll.java:37)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(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$JavaSecurityAccessImpl.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)
Also, once I get this error gone, I will make it so the JFrame jumps around the entire screen, not just 500,500 and below.
the w1 variable is always null is never valorized. you can use this in actionPerformed to make it work this way
#Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
this.setLocation(random, random);
}
}

NullPointerException during writeObject() while using Nimbus Look and Feel

I have 4 classes: TestGUI, MainMenuBar, MainFrame and ProjectToAdd.
MainFrame and ProjectToAdd implements Serializable. When I click on New>Project in MainMenuBar I want to create a new project, new dir for it and in that dir to write a serializable object. When the object has been writen I get NullPointerException (see stacktrace at the end). If I remove Look and Feel part of code in main method I do not get error any more... I'm using NetBeans IDE 8.0.2.
TestGUI code:
package testgui;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class RiskManagerGUI {
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, fall back to cross-platform
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception ex) {
// not worth my time
}
}
new MainFrame().setVisible(true);
}
});
}
}
MainMenuBar code:
package menu_package;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import testgui.MainFrame;
public class MainMenuBar extends JMenuBar{
private MainFrame mainFrame;
public MainMenuBar(MainFrame mainFrame){
this.mainFrame = mainFrame;
JMenu fileMenu = new JMenu("File");
JMenu newMenu = new JMenu("New");
JMenuItem projectMenuItem = new JMenuItem("Project");
projectMenuItem.addActionListener(new AddNewProject());
newMenu.add(projectMenuItem);
fileMenu.add(newMenu);
add(fileMenu);
}
class AddNewProject implements ActionListener {
public void actionPerformed(ActionEvent event) {
mainFrame.addNewProject();
}
}
}
MainFrame code:
package testgui;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import left_panel_package.ProjectsJTree;
import menu_package.MainMenuBar;
public class MainFrame extends JFrame implements Serializable{
private String instalationLocation;
private ArrayList <ProjectToAdd> listOfProjects;
public MainFrame(){
initComponents();
}
public void initComponents() {
setInstalationLocation("C:\\Users\\Pera\\Desktop\\RiskManagerGUI");
listOfProjects = new ArrayList<ProjectToAdd>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("TEST");
setName("mainFrame");
JPanel mainPanel = new JPanel();
setContentPane(mainPanel);
setJMenuBar(new MainMenuBar(this));
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
setSize(width, height);
setLocationRelativeTo(null);
}
public String getInstalationLocation() {
return instalationLocation;
}
private void setInstalationLocation(String instalationLocation) {
this.instalationLocation = instalationLocation;
}
public void addNewProject(){
String nameOfProject = JOptionPane.showInputDialog(null, "Enter the name of new project: ", "Add new project",JOptionPane.OK_CANCEL_OPTION);
if ((nameOfProject != null) && (nameOfProject.length() > 0)) {
try {
ProjectToAdd newProject = new ProjectToAdd(this, nameOfProject);
listOfProjects.add(newProject);
File theDir = new File(newProject.getProjectPath());
theDir.mkdirs();
newProject.writeToFile();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
ProjectToAdd code:
package testgui;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ProjectToAdd implements Serializable{
private String nameOfProject;
private MainFrame mainFrame;
private String projectPath;
public ProjectToAdd (MainFrame mainFrame, String nameOfProject) {
this.mainFrame = mainFrame;
setNameOfProject(nameOfProject);
setProjectPath(mainFrame.getInstalationLocation()+"\\Projects\\"+nameOfProject);
}
public String getNameOfProject() {
return nameOfProject;
}
public void setNameOfProject(String nameOfProject) {
this.nameOfProject = nameOfProject;
}
public void writeToFile() throws IOException{
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(new FileOutputStream(projectPath+
"\\"+nameOfProject+".bin"));
objectOutputStream.writeObject(this);
}
public void readFromFile(){
}
public String getProjectPath() {
return projectPath;
}
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
}
Stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.synth.SynthLookAndFeel.paintRegion(SynthLookAndFeel.java:371)
at javax.swing.plaf.synth.SynthLookAndFeel.update(SynthLookAndFeel.java:335)
at javax.swing.plaf.synth.SynthRootPaneUI.update(SynthRootPaneUI.java:119)
at javax.swing.JComponent.paintComponent(JComponent.java:780)
at javax.swing.JComponent.paint(JComponent.java:1056)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5210)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1579)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1502)
at javax.swing.RepaintManager.paint(RepaintManager.java:1272)
at javax.swing.JComponent._paintImmediately(JComponent.java:5158)
at javax.swing.JComponent.paintImmediately(JComponent.java:4969)
at javax.swing.RepaintManager$4.run(RepaintManager.java:831)
at javax.swing.RepaintManager$4.run(RepaintManager.java:814)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:789)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:738)
at javax.swing.RepaintManager.access$1200(RepaintManager.java:64)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1732)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
The NPE is being thrown because you're trying to serialize MainFrame, an object which contains much GUI detritus, including the Nimbus L&F information, stuff that shouldn't be serialized and looks to be non-serializable. How do I know? Mark that field transient and see what happens:
class ProjectToAdd implements Serializable {
private static final long serialVersionUID = 1L;
private String nameOfProject;
private transient MainFrame mainFrame; // **********
private String projectPath;
If you need to serialize information that's held within the MainFrame, then create a non-GUI model class that contains the key business data from MainFrame and serialize that, not the view -- not the GUI itself. You should in general almost never serialize the view regardless, and it's always a good idea to refactor your program logic out of your view code.
and you were right, this:
objectOutputStream.writeObject(this);
was related to the NPE. Apologies to you.

For loop only executes twice when copying files

I came across a very strange problem in my program I wrote to copy Pictures, Documents, Videos, and Music (from the Windows file system) to a backup drive. I set a string array directories[] equal to {picturesDirectory, documentsDirectory, videosDirectory, musicDirectory} and use a for loop to loop through each one to copy the files. I use a GUI so I have a SwingWorker that runs the actual copy methods. However, when I run the program, it only loops through the "for" loop twice, only copying pictures and documents. I don't think I can really post a SSCCE that will help, so I'm just posting my entire class. inDrive is the main Windows drive ("C" by default), outDrive is the backup drive letter, username is the windows username, and space is the total disk space that the files/directories will take up.
package diana;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
#SuppressWarnings("serial")
public class BasicCopy extends JFrame {
private JPanel contentPane;
private JPanel bottomPane;
private JTextArea txtCopiedDirs;
private JScrollPane scrollPane;
private JButton btnCancel;
private JProgressBar progressBar;
private JLabel lblCopying;
private JLabel lblProgress;
private static String mainDrive;
private static String backupDrive;
private static String username;
private static String backupDir;
double totalSize = 0; //total size of directories/files
double currentMB = 0; //size of already-copied files
static double currentSize = 0; //current size of files counting up to ONE_PERCENT
static int currentPercent = 0; //current progress in %
static double ONE_PERCENT; //totalSize / 100
private ManipulateDirectories md;
private Task task;
public BasicCopy() {
}
public BasicCopy(String inDrive, String outDrive, String username, long space) {
mainDrive = inDrive;
backupDrive = outDrive;
BasicCopy.username = username;
totalSize = space;
ONE_PERCENT = totalSize / 100;
createGUI();
}
public void createGUI() {
// Create frame
setTitle("Backup Progress");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 350);
// Create panel for text area/scroll pane
contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
// Create panel for progress bar/cancel button
bottomPane = new JPanel();
bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.Y_AXIS));
lblCopying = new JLabel("Now backing up your files....\n");
lblCopying.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.add(lblCopying, BorderLayout.NORTH);
// Create text area/scroll pane
txtCopiedDirs = new JTextArea(10, 50);
txtCopiedDirs.setEditable(false);
DefaultCaret caret = (DefaultCaret) txtCopiedDirs.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
scrollPane = new JScrollPane(txtCopiedDirs);
contentPane.add(scrollPane, BorderLayout.CENTER);
lblProgress = new JLabel("Progress:");
progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);
progressBar.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
progressBar.setIndeterminate(true);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Backup Cancelled!");
closeWindow();
}
});
bottomPane.add(lblProgress, Component.LEFT_ALIGNMENT);
bottomPane.add(progressBar, Component.CENTER_ALIGNMENT);
bottomPane.add(btnCancel, Component.RIGHT_ALIGNMENT);
contentPane.add(bottomPane, BorderLayout.SOUTH);
PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if ("progress".equals(event.getPropertyName())) {
currentPercent = (int) event.getNewValue();
progressBar.setValue((int) currentPercent);
progressBar.setString(Integer.toString(currentPercent) + "% ("
+ String.format("%.2f", (currentMB / 1048576))
+ "MB of " + String.format("%.2f", (totalSize / 1048576)) + "MB)");
}
}
};
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);
setVisible(true);
task = new Task();
task.addPropertyChangeListener(listener);
task.execute();
}
/**
* Swing Worker class
*/
class Task extends SwingWorker<Void, String> {
public Task() {
md = new ManipulateDirectories(this);
}
#Override
public Void doInBackground() {
md.makeBackupDirectory();
// Directories to be copied
String pics = mainDrive + ":\\Users\\" + username + "\\Pictures\\";
String docs = mainDrive + ":\\Users\\" + username + "\\Documents\\";
String vids = mainDrive + ":\\Users\\" + username + "\\Videos\\";
String musc = mainDrive + ":\\Users\\" + username + "\\Music\\";
File[] directories = { new File(pics), new File(docs), new File(vids), new File(musc) };
/********** THIS ONLY LOOPS THROUGH PICS AND DOCS **********/
for (int i = 0; i < directories.length; i++) {
md.copyDirectory(directories[i], new File(backupDir));
}
/***********************************************************/
return null;
}
#Override
public void process(List<String> chunks) {
for (String path : chunks) {
txtCopiedDirs.append(path);
}
}
#Override
public void done() {
JOptionPane.showMessageDialog(null, "Backup complete!");
closeWindow();
}
public void updateProgress(int tick) {
if (progressBar.isIndeterminate())
progressBar.setIndeterminate(false);
progressBar.setString(Integer.toString(currentPercent) + "% ("
+ String.format("%.2f", (currentMB / 1048576)) + "MB of "
+ String.format("%.2f", (totalSize / 1048576)) + "MB)");
}
public void publishText(String filename) {
publish(filename + "\n");
}
}
public class ManipulateDirectories {
Task task;
public ManipulateDirectories(Task task) {
this.task = task;
}
public void makeBackupDirectory() {
// Create Backup Directory
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HHmmss");
String timestamp = sdf.format(date);
backupDir = backupDrive + ":\\" + "Backup_" + timestamp;
File backupDirectory = new File(backupDir);
backupDirectory.mkdir();
task.updateProgress(0);
}
// Recursive function to loop through and copy individual files
public void copyDirectory(File file, File dest) {
if (file.isFile()) {
try {
FileUtils.copyFileToDirectory(file, dest);
currentMB = currentMB + getDirSize(file);
currentSize = currentSize + getDirSize(file);
if (currentSize >= ONE_PERCENT) {
currentPercent = currentPercent + (int) (currentSize / ONE_PERCENT);
currentSize = currentSize % ONE_PERCENT;
}
task.updateProgress(currentPercent);
task.publishText(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
} else if (file.isDirectory()) {
File newDir = new File(String.format("%s\\%s", dest.getAbsolutePath(), file.getName()));
if (!newDir.exists()) {
newDir.mkdir();
for (File f : file.listFiles()) {
copyDirectory(f, newDir);
}
}
}
}
public Long getDirSize(File file) {
long size = 0L;
if (file.isFile() && file != null) {
size += file.isDirectory() ? getDirSize(file) : file.length();
} else if (file.isDirectory()) {
for (File f : file.listFiles()) {
size += f.isDirectory() ? getDirSize(f) : file.length();
}
}
return size;
}
}
/* Close current window */
public void closeWindow() {
WindowEvent close = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(close);
System.exit(0);
}
}
I added a comment around the for loop that is only being executed twice. I placed a breakpoint and it never gets there after copying documents, so it must call the SwingWorker's done() method before then.
Does anyone see what might cause this problem? I really hate posting all my code here, as I understand it's often a pain to read through it all. I'm hoping someone can find why it's ending prematurely though. Many thanks!
EDIT:
After further debugging (based on some of the suggestions from the comments), I have discovered there is a NPE due to the program looking for "My Music" within the Documents folder--a "link" that doesn't exist as a directory (hence the null value).
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at javax.swing.SwingWorker.get(Unknown Source)
at diana.BasicCopy$Task.done(BasicCopy.java:181)
at javax.swing.SwingWorker$5.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
at sun.swing.AccumulativeRunnable.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(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)
Caused by: java.lang.NullPointerException
at diana.BasicCopy$ManipulateDirectories.copyDirectory(BasicCopy.java:243)
at diana.BasicCopy$ManipulateDirectories.copyDirectory(BasicCopy.java:244)
at diana.BasicCopy$Task.doInBackground(BasicCopy.java:166)
at diana.BasicCopy$Task.doInBackground(BasicCopy.java:1)
at javax.swing.SwingWorker$1.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at javax.swing.SwingWorker.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I was under the impression I wouldn't have to worry about this since I use the file.isFile() and file.isDirectory() checks. According to the javadocs, these only return true if the file is a file/directory AND if it exists. I assumed (probably stupidly) that it should skip over anything like My Music since it doesn't exist as a directory?
The problem is that the existing java.io.File API can't handle symbolic links (or what ever they call them in Windows). Directories like "My Music" aren't actually a File/directory in the traditional sense, but are a special marker pointing to another file/directory.
In order to overcome this, you'll need to take a look at the new Paths/Files API available in Java 7
For more details, try taking a look at Links, Symbolic or Otherwise
I found the answer. It was the same problem I was asking about in this thread, and was thinking the solution was something else: Java program to calculate directory size keeps throwing NPE
The problem is that file.listFiles() was null when run while the file path was C:\Users\user\Documents\My Music. To fix it I simply put in an if statement to check that file.listFiles() != null before the "for" loop at the bottom of the copyDirectory method:
if (file.listFiles() != null){
for (File f : file.listFiles()) {
copyDirectory(f, newDir);
}
}
I'm sorry for posting this here when apparently I already had the same problem that was answered in another thread. Hopefully this helps someone though. Thank you all for your suggestions, they are appreciated.

MP4 unsupported in JavaFX?

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.

Categories