java.lang.NullPointerException upon file I/O - java

When I run the code, I get an error. The strange thing is when I change files.getTimeScore(); to files.getLineScore();, it executes without errors. However, these functions are almost identical to each other.
When I run the getTimeScore() method from a main in the FileIO class, then it works fine.
Errors
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at tetris.FileIO.loadHighscores(FileIO.java:52)
at tetris.FileIO.getTimeScores(FileIO.java:31)
at tetris.HighScores.<init>(HighScores.java:39)
at tetris.Menu$2.actionPerformed(Menu.java:74)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Code
Highscores class
public HighScores(){
// init A
super("Highscores");
c=getContentPane();
test = new String[100][2];
files = new FileIO();
mainPanel = new JPanel();
test = files.getTimeScores();
timeTable = new JTable(test,timeTitles );
test = files.getLineScores();
lineTable = new JTable(test,lineTitles );
FileIO class
import java.io.File;
import java.io.InputStream;
import java.io.Writer;
import java.util.Scanner;
public class FileIO {
private File file;
private Scanner filescScanner, lineScanner;
private Writer fileWriter, lineWriter;
private String[][] data;
public FileIO () {
data = new String[100][2];
}
public String[][] getLineScores(){
return this.loadHighscores(this.getClass().getResourceAsStream("LineHighscores.txt"));
}
public String[][] getTimeScores(){
return this.loadHighscores(this.getClass().getResourceAsStream("TimeHighscores.txt"));
}
public String[][] loadHighscores( InputStream resourceStream){
int x=0;
String test = "";
filescScanner = new Scanner(resourceStream);
while(filescScanner.hasNextLine()&& x<100) {
lineScanner = new Scanner(filescScanner.nextLine());
lineScanner.useDelimiter("-/-");
data[x][0]=lineScanner.next();//name
data[x][1]=lineScanner.next();//data
x++;
}
lineScanner.close();
filescScanner.close();
return data;
}

You don't test those files can be accessed. i.e. if resourceStream is null.
Using this approach is not idea as you cannot easily update these files if you want add a high score.

line scanner is null for TimeHighscores.txt file. So it means that the while loop was not executed - not even once.

I guess your lineScanner is null. Can't see where you intialize it in FileIO.
You only intialize it in the while-clause.
So if your File is empty, it is still null when you are trying to close it.

Related

Adding FeatureCollection to a FeatureStore throwing AbstractMethodError

This method is supposed to replace the features in the database with new features I pass to it.
private static void replaceBoundaryShape(FeatureCollection<SimpleFeatureType, SimpleFeature> dbFeatures) throws IOException, CQLException{
FeatureStore<SimpleFeatureType, SimpleFeature> fs = null;
FeatureSchemaFactory factory = FeatureSchemaFactory.init();
DataStore geoStore = initDataStore();
try{
fs = (FeatureStore) geoStore.getFeatureSource(factory.getFieldFeatureSchema().getTypeName());
fs.setTransaction(new DefaultTransaction());
for(FeatureIterator<SimpleFeature> iterator = dbFeatures.features(); iterator.hasNext();){
SimpleFeature simpleFeature = iterator.next();
Number fieldId = (Number) simpleFeature.getAttribute(FeatureSchemaFactory.FIELD_ID);
Filter filter = createSearchByIdFilter(fieldId.longValue());
fs.removeFeatures(filter);
}
fs.addFeatures(dbFeatures);
fs.getTransaction().commit();
}catch(CQLException ex){
throw new CQLException(ex.getMessage());
}
}
this is where I create the feature collection passed to replace boundary shape
private static FeatureCollection<SimpleFeatureType, SimpleFeature> createBoundaryFeatures(SimpleFeatureType dbSchema, Collection<FieldFeature> fields){
List<SimpleFeature> result = new ArrayList<SimpleFeature>(fields.size());
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(dbSchema);
for(FieldFeature f: fields){
builder.set("BNDRS", f.getGeometries());
builder.set("FIELD", f.getField());
builder.set("FID", f.getFid());
builder.set("GROWER", f.getGrower());
builder.set("SIMPLIFIED_BNDRS", f.getSimplifiedGeometries());
result.add(builder.buildFeature(null));
}
return DataUtilities.collection(result);
}
This is where I get my field features from a file path and a specified field:
private static Collection<FieldFeature> convertShpFile(String filePath, Field field) throws MalformedURLException, IOException{
#SuppressWarnings("deprecation")
ShapefileDataStore source = new ShapefileDataStore(new File(filePath).toURL());
Collection<FieldFeature> result = new LinkedList<FieldFeature>();
DefaultQuery query = new DefaultQuery();
query.setCoordinateSystemReproject(DefaultGeographicCRS.WGS84);
FeatureCollection queryResult = source.getFeatureSource().getFeatures(query);
FeatureIterator<SimpleFeature> fi = queryResult.features();
while(fi.hasNext()){
SimpleFeature feature = fi.next();
FieldFeature fieldFeature = new FieldFeature();
Object defaultGeometry = feature.getDefaultGeometry();
if(defaultGeometry instanceof Polygon){
Polygon polygon = (Polygon) defaultGeometry;
Polygon[] polygons = {polygon};
defaultGeometry = geometryFactory.createMultiPolygon(polygons);
}
fieldFeature.setField(field.getId());
fieldFeature.setGeometries(defaultGeometry);
fieldFeature.setSimplifiedGeometries(GeoHelper.simplifyGeometry((Geometry) defaultGeometry));
result.add(fieldFeature);
}
fi.close();
source.dispose();
return result;
}
The error occurs on the fs.addFeatures(dbFeatures) line of the replaceBoundaryShape method.
Removing features does not throw an error, but when I call the addFeatures function I receive this AbstractMethodError:
java.lang.AbstractMethodError: org.geotools.jdbc.PreparedStatementSQLDialect.setGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;IILjava/lang/Class;Ljava/sql/PreparedStatement;I)V
The error appears to be thrown when the features are being inserted into the JDBCDataStore
EDIT: Here is the full stack trace
java.lang.AbstractMethodError: org.geotools.jdbc.PreparedStatementSQLDialect.setGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;IILjava/lang/Class;Ljava/sql/PreparedStatement;I)V
at org.geotools.jdbc.JDBCDataStore.insertSQLPS(JDBCDataStore.java:4005)
at org.geotools.jdbc.JDBCDataStore.insert(JDBCDataStore.java:1582)
at org.geotools.jdbc.JDBCDataStore.insert(JDBCDataStore.java:1545)
at org.geotools.jdbc.JDBCInsertFeatureWriter.write(JDBCInsertFeatureWriter.java:76)
at org.geotools.data.InProcessLockingManager$1.write(InProcessLockingManager.java:337)
at org.geotools.data.store.ContentFeatureStore.addFeature(ContentFeatureStore.java:309)
at org.geotools.data.store.ContentFeatureStore.addFeatures(ContentFeatureStore.java:263)
at com.conserviscorp.shape.upload.FieldDAO.replaceBoundaryShape(FieldDAO.java:146)
at com.conserviscorp.shape.upload.FieldDAO.updateFieldData(FieldDAO.java:116)
at com.conserviscorp.ui.MatchedFieldFrame$2.actionPerformed(MatchedFieldFrame.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
The issue was that I was using the wrong version of geotools. When adding items to the dependencies I was using the 10-beta version in some parts, and the current version in other parts.

exception thrown while using .txt in file name

I am trying to run the following code in which i have to save my file as .txt...but whenever I click on 'Save' button..it throws an exception..
Also i want to know how could I save the contents of my textarea line by line in the txt file (including \n).
Here is the code
try
{
int val = jfc.showSaveDialog(jf);
int x =0;
String line;
if(val == JFileChooser.APPROVE_OPTION)
{
File fs=jfc.getSelectedFile();
if(!fs.exists())
{
fs.createNewFile();
FileWriter fw=new FileWriter(fs.getAbsolutePath()+".txt");
BufferedWriter bf=new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new StringReader(ja.getText()));
while((line= br.readLine())!=null)
{
x++;
if(line.charAt(x)=='\n')
fw.write('\n');
else
fw.write(line+"\n");
}
fw.close();
}
else
{
}
}
}
catch(Exception e2)
{
e2.printStackTrace();
JOptionPane.showMessageDialog(null,"Cannot save file");
}
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at notepad$1.actionPerformed(notepad.java:100)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Change your current code from
while((line= br.readLine())!=null)
{
x++;
if(line.charAt(x)=='\n')
fw.write('\n');
else
fw.write(line+"\n");
}
to
while((line= br.readLine())!=null) {
fw.write(line+"\n");
}
You are checking the first char in the first line, the second char in the second line so on.
Try changing
if(line.charAt(x)=='\n')
to
if(line.endsWith('\\n'))
Also you should escape line ends. Use \\n instead of \n.

Get dxdiag results using java

String filePath = "./results.txt";
// Use "dxdiag /t" variant to redirect output to a given file
ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","dxdiag","/t",filePath);
System.out.println("-- Executing dxdiag command --");
Process p = pb.start();
p.waitFor();
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
System.out.println(String.format("-- Printing %1$1s info --",filePath));
while((line = br.readLine()) != null){
if(line.trim().startsWith("Card name:")
|| line.trim().startsWith("Current Mode:")
|| line.trim().startsWith("Display Memory:"))
textArea_3.append(line.trim() + "\n");
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
The error that I get is
java.io.FileNotFoundException: .\results.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at java.io.FileReader.<init>(FileReader.java:58)
at gui.Gui$4.actionPerformed(Gui.java:136)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
I've tried it on Win7 (does not work) and on Win8(it works as expected). If anyone has a thought on what's going on I'd greatly appreciate the help, thx.
It seems to be a relative path problem. I'd recommend trying to add the line System.out.println(new File(filePath).getAbsolutePath()); before instantiating the buffered reader to see where exactly the system tries to look for the results file. You might also want to specify the output location for DXDIAG as an absolute path to ensure the results are stored where you want them to.
1st complete your code your class name missing.
2nd give main method public static void main(String args[]).
3rd take try block.
And 4th last one create TextArea object which is missing in your code :TextArea textArea_3 = new TextArea();
Code will work.

Errors thrown when attemtping to play soung in Java Swing application

Making a Swing application in which a user selects an audio file using a radio button and plays it using the Play button. The GUI class call the method from a custom audio handler class. The audio files are in a package called audio. The following errors are thrown after sound selection and the user clicks the Play button:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at sun.audio.AudioStream.<init>(AudioStream.java:63)
at my.quotesbutton.Player.fear(Player.java:18)
at my.quotesbutton.QuotesButtonUI.jButton3ActionPerformed(QuotesButtonUI.java:221)
at my.quotesbutton.QuotesButtonUI.access$000(QuotesButtonUI.java:16)
at my.quotesbutton.QuotesButtonUI$1.actionPerformed(QuotesButtonUI.java:66)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
The GUI class code as follows:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton1.isSelected()){
Player play = new Player();
try {
play.fear();
} catch (IOException ex) {
Logger.getLogger(QuotesButtonUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (jRadioButton2.isSelected()){
}
else if (jRadioButton3.isSelected()){
}
else if (jRadioButton4.isSelected()){
}
else if (jRadioButton5.isSelected()){
}
else if (jRadioButton6.isSelected()){
}
else {
}
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
The code for the audio handler class as follows:
package my.quotesbutton;
import java.io.*;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Player{
public void fear() throws IOException{
InputStream inputStream = getClass().getResourceAsStream("audio\\fear.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}
}
It seems like you are passing null to the AudioStream constructor. The value you pass it is obtained via getClass().getResourceAsStream().
From Java Class javadoc:
public InputStream getResourceAsStream(String name)
...
Returns:
A InputStream object or null if no resource with this name is found
So, the way this could return null is that the file is not found. The problem is in your file path. The path you are passing is relative. Try finding where your application's work directory is and correct the path relative to it.
EDIT: You can get the working directory via System.getProperty("user.dir").

Game of Life Gridworld NullPointer Run-Time Error

Trying to make Conway's Game of Life using Gridworld.
Everything Compiles but I keep getting the error when i try to take a "step"
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Cell.processSurrondings(Cell.java:27)
at Cell.act(Cell.java:44)
at info.gridworld.actor.ActorWorld.step(ActorWorld.java:68)
at info.gridworld.gui.GUIController.step(GUIController.java:134)
at info.gridworld.gui.GUIController$4.actionPerformed(GUIController.java:247)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Here are the files
lifeWorld (variant of actorWorld)
import info.gridworld.actor.Actor;
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import info.gridworld.grid.UnboundedGrid;
import java.util.ArrayList;
public class lifeWorld extends ActorWorld {
private static final String FIRST_LINE = "Welcome to Ern's Game of Life. (A rip off of Conway's Game of Life)\n" +
"Click a live cell to kill it, a dead cell to resurect it, or run to run the cycles!";
public lifeWorld() {
setGrid(new UnboundedGrid<Actor>());
System.setProperty("info.gridworld.gui.selection", "hide");
System.setProperty("info.gridworld.gui.tooltips", "hide");
System.setProperty("info.gridworld.gui.frametitle", "Ern's Game of Life");
}
private String setMessage() {
return FIRST_LINE;
}
public boolean locationClicked(Location loc) {
if (getGrid().get(loc) == null)
new Cell().putSelfInGrid(getGrid(), loc);
else
getGrid().get(loc).removeSelfFromGrid();
return true;
}
}
Cell (variant of Critter)
import info.gridworld.actor.Actor;
import info.gridworld.grid.Location;
import java.awt.Color;
import java.util.ArrayList;
public class Cell extends Actor {
private boolean planning;
private boolean dies;
private ArrayList<Location> cellsToAdd;
public Cell() {
setColor(Color.BLACK);
planning = true;
dies = false;
}
private void processSurrondings(){
ArrayList<Location> adjCells = getGrid().getOccupiedAdjacentLocations(getLocation());
ArrayList<Location> cellsAdd = new ArrayList<Location>();
if(adjCells.size() > 0)
for(Location a: adjCells)
if(getGrid().getOccupiedAdjacentLocations(a).size() == 3)
cellsToAdd.add(a); //The error happens here apparently
ArrayList<Location> isDead = getGrid().getOccupiedAdjacentLocations(getLocation());
dies = (!(isDead.size() == 2 || isDead.size() == 3));
}
private void executeStep() {
for(Location a: cellsToAdd){
Cell cell = new Cell();
cell.putSelfInGrid(getGrid(),a);
}
if(dies)
removeSelfFromGrid();
}
public void act() {
if (planning) {
processSurrondings();
planning = !(planning);
}
else
this.executeStep();
}
}
GameOfLifeRunner (the runner/driver file)
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.UnboundedGrid;
import info.gridworld.actor.Actor;
public class GameOfLifeRunner {
public static void main(String[] args) {
lifeWorld world = new lifeWorld();
world.show();
}
}
You never initialize the List cellsToAdd in the class Cell:
private ArrayList<Location> cellsToAdd;
causing an NPE to be thrown on this line:
cellsToAdd.add(a);
You could do this in the constructor of Cell:
public Cell() {
cellsToAdd = new ArrayList<Location>();
...
Aside: The preferred approach in Java is to code to an interface. This allows implementations which as List to be easily swapped for other implementations.
private List<Location> cellsToAdd;
See more here and here

Categories

Resources