Automatically resizing a window in JavaFX - java

edit: I'm not sure how to get the stacktrace. Here's the error I get:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Grid hgap=0.0, vgap=0.0, alignment=TOP_LEFTis already inside a scene-graph and cannot be set as root
at javafx.scene.Scene$9.invalidated(Scene.java:1100)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:111)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.Scene.setRoot(Scene.java:1072)
at javafx.scene.Scene.<init>(Scene.java:347)
at javafx.scene.Scene.<init>(Scene.java:223)
at application.Main.start(Main.java:108)
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.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
... 1 more
Exception running application application.Main
I have an assignment where I need to read in information and create a graph from it. It also needs to automatically resize a graph when the user drags the window. I've got the graph working but can't figure out how to get it resize.
I found a different thread that used something like this:
StackPane root = new StackPane(pane);
root.setAlignment(Pos.TOP_LEFT);
// use gridPane size to determine the factor to scale by
NumberBinding maxScale = Bindings.min(root.widthProperty().divide(350),
root.heightProperty().divide(100));
pane.scaleXProperty().bind(maxScale);
pane.scaleYProperty().bind(maxScale);
but that gave me a runtime error.
package application;
import javafx.scene.control.Label;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.NumberBinding;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws FileNotFoundException {
GridPane pane = new GridPane();
pane.setMinSize(400, 500);
pane.setMaxSize(350, 10000);
StackPane root = new StackPane(pane);
ArrayList <Team> aT = new ArrayList <Team>();
Scanner scannerIOInput = null;
FileInputStream fis = null;
BorderPane root2 = new BorderPane();
try{
fis = new FileInputStream(new File("mp3_hockey_stats.txt"));
scannerIOInput = new Scanner(fis);
// System.out.println("File is read in");
String c = null;
int indx;
//read in data
for (int i = 0; i < 7; i++){
c = scannerIOInput.nextLine();
indx = c.indexOf(",");
if (indx > 0)
{
String name = c.substring(0, indx);
String s1 = c.substring(indx + 1);
int stat = Integer.parseInt(s1);
aT.add(new Team (name, stat));
}
}
//print data
int recX, recY, recWidth, recHeight;
recX = 10;
recY = 10;
recWidth = 10;
recHeight = 10;
for (int i = 0; i < aT.size(); i++)
{
Label name = new Label (aT.get(i).teamName1);
Rectangle r = new Rectangle();
r.setX(recX);
r.setY(recY + (i * 100));
r.setWidth(aT.get(i).stats1);
r.setHeight(recHeight);
r.setFill(Color.BLUEVIOLET);
pane.add(name, 1, i);
pane.add(r, 2, i);
//pane.add(" ", 1, i+1);
}
Scene scene = new Scene(pane,350, 100);
primaryStage.setScene(scene);
primaryStage.setTitle("Hockey Statistics Chart");
primaryStage.show();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (NullPointerException e){
System.out.println("NullPointerException.");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException.");
}catch (RuntimeException e){
System.out.println("Runtime exception.");
} finally {
scannerIOInput.close();
}
}
public static void main(String[] args) {
launch(args);
}
}

Related

JavaFX InvocationTargetxception and other errors, trying to display image

I'm sort of a newbie at programming so I apologize if this is sort of a newbie question! I've been exposed to Java somewhat but I'm completely new at JavaFX. I'm trying to write a program that will open a window and display 3 random card images from a deck of 52 cards on a GridPane and I can't seem to figure out why I keep getting InvocationTargetException, RuntimeException, and ArrayIndexOutOfBoundsException. Should I include try and catch blocks, with these exceptions? Or would there be other exceptions I should be including? Or could it be the location of my image files? My current location of all 52 card image files is: C:\Users\Asus\Documents\NetBeansProjects\AdvancedJavaClass\src\Cards
The following is my code:
package Cards;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.util.Random;
public class ThreeCards extends Application {
#Override
public void start(Stage primaryStage) {
Image[] Cards = new Image[51];
ImageView firstCard = new ImageView();
ImageView secondCard = new ImageView();
ImageView thirdCard = new ImageView();
Random cardPicker = new Random();
int card1 = 0;
int card2 = 0;
int card3 = 0;
for(int i=1; i<53; i++) {
Cards[i-1] = new Image("file: "+i+".png");
}
if (card1 == card2 || card2 == card3 || card3 == card1) {
card1 = cardPicker.nextInt(51)+0;
card2 = cardPicker.nextInt(51)+0;
card3 = cardPicker.nextInt(51)+0;
}
firstCard.setImage(Cards[card1]);
secondCard.setImage(Cards[card2]);
thirdCard.setImage(Cards[card3]);
GridPane root = new GridPane();
root.getChildren().add(firstCard);
root.getChildren().add(secondCard);
root.getChildren().add(thirdCard);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Three Cards");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
And the following is what happens/what I get when I run it:
Executing C:\Users\Asus\Documents\NetBeansProjects\AdvancedJavaClass\dist\run2133970792\AdvancedJavaClass.jar using platform C:\Program Files\Java\jdk1.8.0_71\jre/bin/java
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$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 51
at Cards.ThreeCards.start(ThreeCards.java:34)
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 Cards.ThreeCards
Java Result: 1
The IDE I am currently using is Netbeans.
Please help! I can't figure out why I'm getting these errors! Thank you!!
Change this:
for(int i=1; i<53; i++) {
Cards[i-1] = new Image("file: "+i+".png");
}
To:
for(int i=0; i<51; i++) {
Cards[i] = new Image("file: "+ String.valueOf(i+1) +".png");
}
You are over-indexing your array (Cards[51] does not exist).

NullPointerException Error on simple program [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 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.

Program doesn't start when I use mediaPlayer

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());

Why is my program after compiling with javapackager couldn't run even though compiling with javac went fine?

I've encountered a problem like this. Here's my code:
package pdfex;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.FileChooser;
import javafx.geometry.*;
import javafx.scene.paint.Color;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.lang.*;
import java.util.*;
import java.util.HashMap;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.ColumnText;
//import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Element;
public class PdfExport extends Application {
public static void main(String[] args) {
launch(args);
}
File filePDF;
File fileCos;
File fileWmark;
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("PDF Export");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("PDF Export");
scenetitle.setFont(Font.font("Tahoma",FontWeight.NORMAL,20));
grid.add(scenetitle, 0, 0, 2, 1);
Label openPwd = new Label("Open Password");
grid.add(openPwd, 0, 1);
TextField userTextField = new TextField();
userTextField.getText();
grid.add(userTextField, 1, 1);
Label homePwd = new Label("Home Password");
grid.add(homePwd, 0, 2);
TextField pwBox = new TextField();
pwBox.getText();
grid.add(pwBox, 1, 2);
Label labelCos = new Label();
//final String cos = new String();
Button btnBrowse = new Button("List of Companies");
final StringBuilder cos = new StringBuilder();
btnBrowse.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
FileChooser listChooser = new FileChooser();
//Set filter TEXT file
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TEXT Files (*.txt)", "*.txt");
listChooser.getExtensionFilters().add(extFilter);
fileCos = listChooser.showOpenDialog(primaryStage);
String filePathCos = fileCos.getAbsolutePath();
labelCos.setText(filePathCos);
cos.append(filePathCos);
}
});
HBox hbBtnBrowser = new HBox(10);
hbBtnBrowser.setAlignment(Pos.CENTER);
hbBtnBrowser.getChildren().addAll(btnBrowse, labelCos);
grid.add(hbBtnBrowser, 1, 3);
Label labelPDF = new Label();
//final String pdf = new String();
Button btnBrowse2 = new Button("Look for PDF files");
final StringBuilder pdf = new StringBuilder();
btnBrowse2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
FileChooser pdfFile = new FileChooser();
// Set extension filtre
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF Files (*.pdf)", "*.pdf");
pdfFile.getExtensionFilters().add(extFilter);
// Show open file dialog
filePDF = pdfFile.showOpenDialog(primaryStage);
String filePathPDF = filePDF.getAbsolutePath();
labelPDF.setText(filePathPDF);
pdf.append(filePathPDF);
}
});
HBox hbBtnBrowse2 = new HBox(10);
hbBtnBrowse2.setAlignment(Pos.CENTER);
hbBtnBrowse2.getChildren().addAll(btnBrowse2, labelPDF);
grid.add(hbBtnBrowse2, 1, 4);
// Watermark File
Label labelWatermark = new Label();
//final String wmark = new String();
Button btnWmark = new Button("Watermark?");
final StringBuilder wmark = new StringBuilder();
btnWmark.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
FileChooser wmarkFile = new FileChooser();
fileWmark = wmarkFile.showOpenDialog(primaryStage);
String filePathWmark = fileWmark.getAbsolutePath();
labelWatermark.setText(filePathWmark);
wmark.append(filePathWmark);
}
});
HBox hbBtnBrowse3 = new HBox(10);
hbBtnBrowse3.setAlignment(Pos.CENTER);
hbBtnBrowse3.getChildren().addAll(btnWmark, labelWatermark);
grid.add(hbBtnBrowse3, 1, 5);
//grid.setGridLinesVisible(true);
Button btn = new Button("Exporting PDF");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(btn);
grid.add(hbBtn, 2, 7);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 9);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
long startTime = System.currentTimeMillis();
//System.out.println(cos.toString());
actiontarget.setFill(Color.BLACK);
try {
BufferedReader br = new BufferedReader(new FileReader(cos.toString()));
String line;
String user = userTextField.getText();
byte[] USER = user.getBytes();
String owner = pwBox.getText();
byte[] OWNER = owner.getBytes();
if(user != owner) {
try{
while ((line = br.readLine()) != null) {
try {
String a = line;
PdfReader Post_Survey = new PdfReader(pdf.toString());
int number_of_pages = Post_Survey.getNumberOfPages();
// Naming PDF files
PdfStamper stamp = new PdfStamper(Post_Survey, new FileOutputStream(line + ".pdf"));
// set Security
stamp.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
// Update Metadata
HashMap<String, String> hMap = Post_Survey.getInfo();
hMap.put("Title", "Post Survey Highlights");
hMap.put("Subject", "Market Highlights");
hMap.put("Creator", "Zestiremia");
hMap.put("Keywords"," \n * * * * * \n * * \n * * * * * * \n * * * \n * * * \n * * * * * * \n * * \n * * \n * * * * * * * * \n ");
hMap.put("Author", "SSC-Talentnet");
stamp.setMoreInfo(hMap);
int i = 0;
Image watermark_image = Image.getInstance(wmark.toString());
BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ITALIC, BaseFont.WINANSI, BaseFont.EMBEDDED);
watermark_image.setAbsolutePosition(430, 10);
PdfContentByte add_watermark;
PdfContentByte add_text;
//start stamping!!
while (i < number_of_pages) {
i++;
// watermark image
add_watermark = stamp.getOverContent(i);
add_watermark.addImage(watermark_image);
// set where lines are
add_text = stamp.getOverContent(i);
add_text.setFontAndSize(bf, 12);
ColumnText.showTextAligned(add_text,Element.ALIGN_LEFT, new Phrase("This is the properties of blah blah and is solely used for " + line + " only!"), 20, 20, 0);
}stamp.close();
//Post_Survey.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}catch (IOException e) {
e.printStackTrace();}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
actiontarget.setText("What up yo! It's all done.\nThe whole process has taken up to "+totalTime/1000+"s.\nYou've done a great job!");
//System.out.println("What up yo!!!");
}
});
primaryStage.setScene(new Scene(grid, 550, 300));
primaryStage.show();
}
}
If I compile
PS D:\Documents\javafx> javac PdfExport.java
in the folder pdfex, then
cd ..
and run,
`java pdfex.PdfExport the program goes just fine.
However, if I run the following:
PS D:\Documents\javafx> javac -d classes PdfExport.java
PS D:\Documents\javafx> javapackager -createjar -appclass pdfex.PdfExport -srcdir classes -outdir dist -outfile pdfex2.jar -v
The comilation went fine, but when I run the program,
PS D:\Documents\javafx\dist> java -jar pdfex2.jar
here's what I got:
Exception in thread "JavaFX Application Thread" java.lang.NoClassDefFoundError: com/itextpdf/text/pdf/PdfReader
at pdfex.PdfExport$4.handle(PdfExport.java:232)
at pdfex.PdfExport$4.handle(PdfExport.java:199)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/96639997.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.text.pdf.PdfReader
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 48 more
`
Any idea why?
If you use java -jar you need to reference other java libs in the MANIFEST of your jar
Like tomsontom said, the Java runtime is looking for classes/libraries that aren't available.
A popular approach is to set up your project to use Maven. Maven can pull libraries in from maven central. Then you can use the maven shade plugin to create your .jar, with the libraries packaged up inside of it.
Another option is to use Gradle, another build tool.

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.

Categories