Exception in thread "AWT-EventQueue-0" - java

I am currently doing a project on steganography using discrete Wavelet Transform.I have already written the code and compiled it.However I am facing some exceptions.Kindly help me interpret the exceptions.
The exception is as follows
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DWT.dwtFunc(Steganography.java:292)
at TextInput.actionPerformed(Steganography.java:252)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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 am new in Stack Overflow.Forgive me if I have made any mistake while posting the question.
Thank You
Re:
Sorry Sir I am still getting acquainted to the rules of the forum.
The code for detection of skin region in an image is
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.lang.*;
public class demo2
{
public void skindet()
{
float[] hsvval;
float hue,sat,val;
int counter = 0;
String[] skinpixel = new String[200000];
int scount = 0;
try
{
BufferedImage image = ImageIO.read(new File("lena.png"));
int[][] rgb=new int[550][550];
int w = image.getWidth();
int h = image.getHeight();
hsvval=new float[3];
int red,green,blue;
for (int i=0;i<w;i++)
{
for (int j=0;j<h;j++)
{
rgb[i][j] =image.getRGB(i,j);
red=(rgb[i][j] >> 16) & 0xff;
green=(rgb[i][j] >> 8) & 0xff;
blue=(rgb[i][j]) & 0xff;
float[] values = Color.RGBtoHSB(red,green,blue,null);
for(int s=0;s<3;s++)
{
hsvval[counter]=values[s];
counter++;
}
hue=hsvval[0];
sat=hsvval[1];
val=hsvval[2];
if(hue>0 && hue<0.11 && sat>0.2 && sat<0.7)
{
String xcor=Integer.toString(i);
String ycor=Integer.toString(j);
skinpixel[scount]=xcor;
scount++;
skinpixel[scount]=ycor;
scount++;
}
}
}
int length=skinpixel.length;
for(int i=0;i<length;i++)
System.out.println(skinpixel[i]+"\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
demo2 dem=new demo2();
dem.skindet();
}
}
The exception is
java.lang.ArrayIndexOutOfBoundsException: 3
at demo2.skindet(demo2.java:44)
at demo2.main(demo2.java:79)
Thank You for replying.Regards

It means that you're calling Integer.parseInt from line 292 of Steganography.java (which unusually appears to hold a class called DWT rather than Steganography), but you're providing a null value.
It looks like this is in response to some action being performed on a text field.
We can't really tell a lot more without seeing your code - you need to work out why the value is null.
EDIT: Okay, now that it's changed to a completely different error, this is the problem:
int counter = 0;
hsvval=new float[3];
...
for (int i=0;i<w;i++)
{
for (int j=0;j<h;j++)
{
...
for(int s=0;s<3;s++)
{
hsvval[counter]=values[s];
counter++;
}
...
}
}
So the first time the inner loop is executed, it's fine - but on the second iteration of the middle loop (j = 1), you haven't reset counter, so it's 3 - which is out of range. You've got the same problem with scount later.
If you declare and initialize count and scount just before they're used in the inner loop, it's fine.

Related

NullPointerException and IllegalArgumentException when trying to load images in Java

I have looked all over StackOverflow trying to find a solution for this but it's just kicking my ass. I have to remake Space Invaders for a class project and I need to load in the images (.gif files) using ImageIO.
I have all of my images and sound files in the source folder as shown below.
class structure
Whenever I use new File(/SItop0.gif"), it gives me an IIOException. Why can't I load my images in?
Here is my code:
public BufferedImage getImage() {
try {
BufferedImage image = ImageIO.read(new File(/SItop0.gif")); // Line 30: this is the same for SITop, SIMiddle, and SIBottom. I'm just getting different images for each.
return image;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
That is in the class for the object I want to draw on the panel, and the code below is in the class for the panel in which I call the method:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 10; j++) {
if(i == 0) {
SITop invader = new SITop();
g.drawImage(invader.getImage(), 75+35*j, 80+25*i, null);
}
if(i == 1 || i == 2) {
SIMiddle invader = new SIMiddle();
g.drawImage(invader.getImage(), 75+35*j, 80+25*i, null);
}
if(i == 3 || i == 4) {
SIBottom invader = new SIBottom();
g.drawImage(invader.getImage(), 75+35*j, 80+25*i, null); // Line 42
}
}
}
}
This is the error I get:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at SIBottom.getImage(SIBottom.java:30)
at SIPanel.paintComponent(SIPanel.java:42)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at java.awt.Window.paint(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.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)
at java.awt.EventDispatchThread.run(Unknown Source)
EDIT:
I changed the line to BufferedImage image = ImageIO.read(new File("Assets/SItop0.gif")); and changed the method to overwriting the paintComponent and now it opens up the frame and the panel but it doesn't seem to draw anything. The screen is just black.
EDIT 2:
Changed the code in my question to coincide with the code I'm using now.

Save Word-file with Java (runnable JAR)

I´m trying to build an application which can read information from Excel files and place the data into a document. The document is a form of a template with columns in. Everything works just fine until the saving part.
It work, almost, like it should when I run the program directly in IntelliJ. However, when I install the application to an runnable JAR with Maven - the JAR won't work.
The file is saved as desired... But the new file contains nothing if I run the application from JAR. When i run directly in IntelliJ, the new file is been created and opened, but of 3 columns / row, only 2 has data in it.
What can I do?
Link to template document
http://www.labelmedia.de/englisch/doc/70%20x%2032%20mm%20-%20Art.%2088%2010%2027%2070%2032.doc
Thank you in advanced
package utils;
import model.Customers;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class WriteToDocument {
String TARGET_FILE = "src\\main\\java\\utils\\template\\template.doc";
private int postInList = 0;
public WriteToDocument() {}
public WriteToDocument(ArrayList<Customers> list) throws IOException {
list.remove(0);
HWPFDocument doc = null;
try {
doc = openDocument(TARGET_FILE);
Range range = doc.getRange();
TableIterator itr = new TableIterator(range);
while (itr.hasNext()) {
Table table = itr.next();
for (int rowIndex = 0; rowIndex < table.numRows(); rowIndex++) {
TableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.numCells(); colIndex++) {
TableCell cell = row.getCell(colIndex);
//WRITE IN TABLE //
if (postInList < list.size()) {
cell.getParagraph(0).replaceText(list.get(postInList).getName() + "\n\r" +
"\n\r" + list.get(postInList).getAddress() + "\n\r" +
list.get(postInList).getPostcode() + " " + list.get(postInList).getCity(), false);
postInList++;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
saveDocument(doc);
}
}
private HWPFDocument openDocument(String file) throws Exception {
System.out.println("OPEN");
return new HWPFDocument(new POIFSFileSystem(new FileInputStream(file)));
}
private static void saveDocument(HWPFDocument doc) throws IOException {
System.out.println("SAVE");
try (FileOutputStream out = new FileOutputStream(new File("test.doc"))) {
doc.write(out);
out.flush();
System.out.println("File saved");
doc.close();
out.close();
Desktop dt = Desktop.getDesktop();
dt.open(new File("test.doc"));
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
Stacktrace
java.io.FileNotFoundException: src\main\java\utils\template\template.doc (Det går inte att hitta sökvägen)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at utils.WriteToDocument.openDocument(WriteToDocument.java:56)
at utils.WriteToDocument.<init>(WriteToDocument.java:25)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
at java.awt.EventDispatchThread.run(Unknown Source)
SAVE
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at utils.WriteToDocument.saveDocument(WriteToDocument.java:62)
at utils.WriteToDocument.<init>(WriteToDocument.java:49)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
at java.awt.EventDispatchThread.run(Unknown Source)
Most probably you are missing libraries when it is exported as a JAR. You are using Apache POI as external libraries. Inside the IDE all the libraries were applied but when exported, they seems to be missing. Just run the jar file from command prompt to be 100% clear about the issue. In IDEs like NetBeans the libraries are exported into a separate folder called lib have a look for similar related to your IDE as well.

Move a file to a specific folder

I'm trying to move a file to a specified folder but I can't.
This is the code:
public static void moveToRightDirectory(File song, String album) throws IOException {
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
String pathDirectory = selectedDir + "\\" + album;
File dir = new File(pathDirectory);
System.out.println("dir.exists(): " + dir.exists());
if(dir.exists()) {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
}
else {
boolean success = (new File(pathDirectory)).mkdirs();
if(!success) {
System.out.println("Error creating directory.");
}
else {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
//FileUtils.moveFile(song, dir);
}
}
}
I know there are other message about this (from these I was inspired) but I wasn't able to solve so I would ask for your help.
I would like to move the song file in the folder dir. To do this I have tried several methods:
Files.move -> The following errors are generated:
Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Trailing char < > at index 55: C:\Users...\dir
at sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at java.io.File.toPath(Unknown Source)
at createDir.CreateDirectory.moveToRightDirectory(CreateDirectory.java:73)
at createDir.CreateDirectory.createDirectory(CreateDirectory.java:40)
at gui.DirChooser.actionPerformed(DirChooser.java:54)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
song.renameTo(dir) -> It does nothing.
FileUtils.moveFile(song, dir); -> Eclipse does not find FileUtils. I did the import of java.lang.Object.org.apache.commons.io.FileUtils but the error becomes "The import java.lang.Object.org can not be resolved."
How can I fix?
Thanks a lot.
Not an answer to the actual question, but, based on the error message
java.nio.file.InvalidPathException: Trailing char < > at index 55:
I'm guessing your code isn't getting rid of the trailling whitespaces properly.
Try
album = album.trim();
Instead of
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
Maybe this will be of assistance
Step 1 : Rename File
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Step 2: Copy and delete
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}

Nullpointers in java and how to overcome those?

Say for example, if in a program you get a null-pointer error for adding a piece of code to your which program makes the program run fine but without that piece of code the program doesn't work as expected, would it be a good idea to allow the null-pointer error to happen, if so, is there any way of catching it before it displays onto the console. 1 way I am aware of is, using try and catch but in my past experience this hasn't worked, my attempt at using this might be wrong, but this is how I tried it.
try {
// line / s of code to catch the error from
} catch (java.lang.NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edited: The list of error i am getting:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at playAGame.endGameResult(playAGame.java:204)
at playAGame.checkingWinner(playAGame.java:159)
at playAGame.callCheckWinner(playAGame.java:179)
at playAGame.moveSetup(playAGame.java:66)
at playAGame$1.actionPerformed(playAGame.java:52)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
this is because of this line: button = new JButton[button.length][button.length];
I am creating a TicTacToe game and if I remove that line from my code, the game won't work properly.
edited: I believe this is one of the lines providing the null pointer, correct me if I am wrong. Basically, I have created a method checking if three given buttons have the value X, if it does then trigger the win variable to true. This is how I am checking if someone has won the TicTacToe game.
public void checkingWinner(JButton button1, JButton button2, JButton button3) {
if(buttonA.getText().equals(buttonB.getText()) && buttonB.getText().equals(buttonC.getText()) && buttonA.getText().equals("X"))
{
win = true;
System.out.pl("winner is X");
}
It's hard to tell without seeing the whole code, but it might be the case that the initialization you're doing of the array is throwing an exception since it's the first time it's being initialized, during which time it is being referenced.
If that's the case, you should solve this by using a constant for the width and height instead of self reference:
public static final int HEIGHT = ...;
public static final int WIDTH = ...;
...
button = new JButton[HEIGHT][WIDTH];
Are you sure that the line/s of code are throwing a NullPointerException? Because it works for me.
public class Main {
static String a;
public static void main(String args[]) {
try {
a.charAt(0);
} catch (java.lang.NullPointerException e) {
System.out.println("Thrown");
e.printStackTrace();
}
}
}

Getting an exception as I create several labels off an array in Java (Swing)

as the title says, I'm getting a bunch of exceptions while trying to create several labels off an array into a GridLayout of a 100x100 cells, I believed it was supposed to fit perfectly but as I try to create the Tiles (which are merely an exception to JLabel with x,y and type variables) inside the panel which would represent the map, it seems that something is having trouble drawing them somewhere, been trying to use debug but haven't got any useful information about why it's happening.
This is the pertinent code (don't know if pastebin is against the rules, but it will make my life easier showing it to you all)
GUI class:
package gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUIJuego extends JFrame{
private JButton botonConstruirEscuela = new JButton("Escuela");
private JButton botonConstruirComisaria = new JButton("Comisaria");
private JButton botonConstruirCuartel = new JButton("Cuartel de Bomberos");
private JButton botonConstruirArbol = new JButton("Arbol");
private JButton botonConstruirCasa = new JButton("Casa");
private JButton botonConstruirComercio = new JButton("Comercio");
private JButton botonConstruirIndustria = new JButton("Industria");
private Tile[][] mapaTiles = new Tile[100][100];
private JLabel arcaLabel = new JLabel("Arca");
private JLabel puntosBellezaLabel = new JLabel("Puntos de Belleza");
private JLabel habitantesLabel = new JLabel("Habitantes");
public GUIJuego(){
JPanel panelConstruccion = new JPanel(new GridLayout(7,1));
JPanel panelDatosCiudad = new JPanel(new GridLayout(1,3));
JPanel panelMapa = new JPanel(new GridLayout(100,100));
add(panelConstruccion, BorderLayout.WEST);
panelConstruccion.add(botonConstruirEscuela);
panelConstruccion.add(botonConstruirComisaria);
panelConstruccion.add(botonConstruirCuartel);
panelConstruccion.add(botonConstruirArbol);
panelConstruccion.add(botonConstruirCasa);
panelConstruccion.add(botonConstruirComercio);
panelConstruccion.add(botonConstruirIndustria);
add(panelDatosCiudad, BorderLayout.NORTH);
panelDatosCiudad.add(arcaLabel);
panelDatosCiudad.add(puntosBellezaLabel);
panelDatosCiudad.add(habitantesLabel);
add(panelMapa, BorderLayout.CENTER);
cargarTiles(panelMapa);
}
private void cargarTiles(JPanel panel){
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
mapaTiles[i][j] = new Tile(i, j, 0);
asignarTile(mapaTiles[i][j], panel);
}
}
}
private void asignarTile(Tile tile, JPanel panel){
if(tile.getTipo() == 0){
tile.setText("Pasto");
panel.add(tile);
}
}
}
This is an isolated GUIJuego class, showing what I believe is causing problems:
public class GUIJuego extends JFrame{
private Tile[][] mapaTiles = new Tile[100][100];
public GUIJuego(){
JPanel panelMapa = new JPanel(new GridLayout(100,100));
add(panelMapa, BorderLayout.CENTER);
cargarTiles(panelMapa);
}
private void cargarTiles(JPanel panel){
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
mapaTiles[i][j] = new Tile(i, j, 0);
asignarTile(mapaTiles[i][j], panel);
}
}
}
private void asignarTile(Tile tile, JPanel panel){
if(tile.getTipo() == 0){
tile.setText("Pasto");
panel.add(tile);
}
}
}
I believe the issue is within the GUI Class, the demise of my application starting at line 50. This is the dump of the errors it gives me:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getDefaultComponent(Unknown Source)
at java.awt.FocusTraversalPolicy.getInitialComponent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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.SequencedEvent.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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getDefaultComponent(Unknown Source)
at java.awt.FocusTraversalPolicy.getInitialComponent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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.SequencedEvent.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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)
EDIT: Tile Class
import javax.swing.JLabel;
public class Tile extends JLabel{
private int x, y, tipo;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getTipo(){
return tipo;
}
public void setTipo(int tipo){
if(tipo >= 0 || tipo <= 6)
this.tipo = tipo;
}
public Tile(int x, int y, int tipo) {
this.setX(x);
this.setY(y);
this.setTipo(tipo);
}
}
New information:
What is that black block?
That's what I get in the panel where the map is supposed to be, I don't know if that makes my issue clearer.
Thanks for reading!
In the Tile class don't override getX() and getY() methods. Those are methods defined by JComponent().
Instead maybe use getRow() and getColumn() along with setRow() and setColumn().

Categories