Game of Life Gridworld NullPointer Run-Time Error - java

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

Related

java.lang.NumberFormatException: empty String

The code below keeps giving a java.lang.NumberFormatException: empty String:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
double AText = Double.parseDouble(angleAField.getText());
double BText = Double.parseDouble(angleBField.getText());
double CText = Double.parseDouble(angleCField.getText());
double aText = Double.parseDouble(sideaField.getText());
double bText = Double.parseDouble(sidebField.getText());
double cText = Double.parseDouble(sidecField.getText());
if (getMissing(angleAField.getText()) == false && getMissing(angleCField.getText()) == false) { //doesnt have angle C ,find Angle A
double angleA = Math.round(Math.asin((Math.sin(BText) / bText) * aText));
angleAField.setText("" + angleA);
}
}
public boolean getMissing(String Field) {
try {
if (Field.equals("")) {
return false; // has number
}
} catch (NumberFormatException e) {}
return true;
}
Error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at sowhatstrig.trigFrame.jButton4ActionPerformed(trigFrame.java:520)
at sowhatstrig.trigFrame.access$300(trigFrame.java:20)
at sowhatstrig.trigFrame$4.actionPerformed(trigFrame.java:353)
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: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)
You should check your field before parse double:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
double AText = ParseDouble(angleAField.getText());
double BText = ParseDouble(angleBField.getText());
double CText = ParseDouble(angleCField.getText());
double aText = ParseDouble(sideaField.getText());
double bText = ParseDouble(sidebField.getText());
double cText = ParseDouble(sidecField.getText());
// other code here same
}
double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
try {
return Double.parseDouble(strNumber);
} catch(Exception e) {
return -1; // or some value to mark this field is wrong. or make a function validates field first ...
}
}
else return 0;
}
The string you're trying to parse as double is empty. You need to check if the getText() method returns a non empty string before trying to do the parsing cause you can't parse to double an empty string.

Java- RuntimeException- Uncompilable source code - Erroneous tree type

I'm new in Java also I'm new in this website, so I'm sorry if the error is obvious, but I got an error, that I dont know what it means, I have try everything to fix it.
I'm currently writing a basic aplication library, with some swing interface, but the problem is when trying to create a window of the form of books, there is the relevant code.
This is the principal window.
public class VentanaPrincipal extends javax.swing.JFrame {
public VentanaPrincipal() {
initComponents();
this.setLocationRelativeTo(null);
}
private void bt_salirActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
EscribirBinario escritor = new EscribirBinario();
// Collections.sort(ListaClientes.clientes);
if (escritor.abrir(Main.archivo1)) {
for (int indice = 0; indice < ListaClientes.clientes.size(); indice++) {
escritor.escribir(ListaClientes.clientes.get(indice));
}
escritor.cerrar();
}
System.exit(0);
}
private void bt_clienteActionPerformed(java.awt.event.ActionEvent evt) {
MantenimientoCliente clientes = new MantenimientoCliente(this, true);
clientes.setVisible(true);
}
private void bt_libroActionPerformed(java.awt.event.ActionEvent evt) {
MantenimientoLibro book = new MantenimientoLibro(this, true);
book.setVisible(true);
}
}
There are the code of the form of books.
public class MantenimientoLibro extends javax.swing.JDialog {
public MantenimientoLibro() {
}
public MantenimientoLibro(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
}
public MantenimientoLibro(java.awt.Dialog parent, boolean modal) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
}
private void bt_salirActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
private void bt_insertarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
FormularioLibro formulario = new FormularioLibro(this, true);
formulario.setVisible(true);
this.dispose();
}
}
And this is the error i got:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: TareaP2.MantenimientoLibro
at TareaP2.VentanaPrincipal.bt_libroActionPerformed(VentanaPrincipal.java:130)
at TareaP2.VentanaPrincipal.access$100(VentanaPrincipal.java:11)
at TareaP2.VentanaPrincipal$2.actionPerformed(VentanaPrincipal.java:51)
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.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
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)
Have a look at the bug report here. It has the solution to your problem:
From the nbusers mailing list I got the following hint:
"workaround it by deselecting 'Compile On Save' in the project options".
The answer pointed out by Mark in the comments also goes along the same line. Here is the link again:
java.lang.RuntimeException: Uncompilable source code - what can cause this?
Exiting Netbeans and starting the compilar again resolved the issue.

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").

How to open new JFrame instead of using this

Everytime i wanted to open a new window when a button is clicked i have used this:
String password = new String(TextoContraseña.getPassword());
String nombre = (String)BotonNombreOperario.getSelectedItem();
if(!nombre.equals("Seleccione")) {
if (Trabajo.validarOperario(nombre,password)) {
Inicio.setNombreLogin(nombre);
OpcionesOperario rec = new OpcionesOperario();
if (JOptionPane.showConfirmDialog(this,rec,(String)BotonNombreOperario.getSelectedItem(), JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE)==JOptionPane.OK_OPTION){
} // this open the new window
} else {
JOptionPane.showMessageDialog(null, "Contraseña incorrecta");
}
} else {
JOptionPane.showMessageDialog(null, "Seleccione a un operario");
}
The thing is that i know that is not the correct way of doing this, because i'm using a JOptionPane which is not used for select any option but to open a new window.
The thing is that i want to do it right using a JFrame. For example i changed "OpcionesOperario" to extends JFrame instead of extends JPanel.
Also i changed in Inicio this code
Inicio.setNombreLogin(nombre);
OpcionesOperario rec = new OpcionesOperario();
rec.setVisible(true);
Inicio.super.dispose();
But i get an error when i use rec.setVisible(true). I think is because i have no idea of using a JFrame, so i would appreciate some help. I know is a weird way of doing it, that's why i want to change if i can, because all the program works perfectly.
My OpcionesOperario class is:
public class OpcionesOperario extends javax.swing.JPanel {
/**
* Creates new form OpcionesOperario
*/
String aux;
boolean realizado = false;
boolean realizado1 = false;
boolean realizado2 = false;
public static String textoImprimible;
String actividad;
public OpcionesOperario() {
initComponents();
for (Producto p : Trabajo.getProductos()) {
jComboBox1.addItem(p.getiD_Producto());
}
aux=" ---------------------------------------------------------------------\r\n";
aux+=" Listado de Registros\r\n";
aux+=" ---------------------------------------------------------------------\r\n\r\n";
for (Trabajador t : Trabajo.getTrabajadores()) {
if ((!t.getTipoEmpleado().equals("Sudo")) && (!t.getTipoEmpleado().equals("Administrador"))) {
if (t.getNombre().equals(Inicio.getNombreLogin())) {
if (t.isActividadIniciada()){
BotonInicio.setEnabled(false);
textoVariante.setText("Actividad en curso...");
actividad = t.getActividad();
jComboBox2.setSelectedItem(actividad);
jComboBox2.setEnabled(false);
} else {
BotonFinal.setEnabled(false);
textoVariante.setText("Iniciar para comenzar");
textoVariante.setForeground(Color.red);
}
}
}
}
}
i have more methods but i don't think it is useful for the problem
The problem i get is:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: trabajo/OpcionesOperario$5
at trabajo.OpcionesOperario.initComponents(OpcionesOperario.java:163)
at trabajo.OpcionesOperario.<init>(OpcionesOperario.java:40)
at trabajo.Inicio.BotonOKActionPerformed(Inicio.java:325)
at trabajo.Inicio.access$500(Inicio.java:24)
at trabajo.Inicio$6.actionPerformed(Inicio.java:192)
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.AbstractButton.doClick(AbstractButton.java:356)
at trabajo.Inicio$1.actionPerformed(Inicio.java:45)
at javax.swing.JTextField.fireActionPerformed(JTextField.java:508)
at javax.swing.JTextField.postActionEvent(JTextField.java:721)
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2926)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
at java.awt.Component.processEvent(Component.java:6282)
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.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1895)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:762)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1027)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:899)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:727)
at java.awt.Component.dispatchEventImpl(Component.java:4731)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
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)
Caused by: java.lang.ClassNotFoundException: trabajo.OpcionesOperario$5
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 51 more
I have changed to JFrame and i still get problems in the line where i say "rec.setVisible(true)". I will put the code of the constructor of Inicio which is the main class.
public Inicio() {
initComponents();
setIconImage(new ImageIcon(getClass().getResource("/Imagenes/Icono.png")).getImage()); // Esto es para cambiar el iconito de java
this.centerScreen(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //this is new
for (Trabajador t : Trabajo.getTrabajadores()) {
if ((!t.getTipoEmpleado().equals("Sudo")) && (!t.getTipoEmpleado().equals("Administrador"))) {
BotonNombreOperario.addItem(t.getNombre()); //Meter en combobox solo los operarios
}
}
TextoContraseña.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BotonOK.doClick(); //darle a intro tambien entra
}
});
}
I think the problem is about Netbeans
Try this:
Go to C:\Users\yourname\.netbeans\yourversion and delete the content.Then try to compile again.

java.lang.NullPointerException upon file I/O

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.

Categories

Resources