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.
Related
So, I've been looking a while for a solution to my problem, but it just doesn't work. Here is the piece of code that is giving me problems:
else if(xy==true || xz==true)
{
mm1.setVisible(true);
mm2.setVisible(true);
mm1.repaint();
mm2.repaint();
SwingUtilities.updateComponentTreeUI(this);
this.validateTree();
sound = java.applet.Applet.newAudioClip(getClass().getResource("/sonido/monster.wav"));
sound.play();
sound1 = java.applet.Applet.newAudioClip(getClass().getResource("/sonido/grito.wav"));
sound1.play();
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
Logger.getLogger(formulario2.class.getName()).log(Level.SEVERE, null, ex);
}
formulariogame over2=new formulariogame();
over2.setVisible(true);
this.dispose();
}
I've tried using the "synchronized" method, using repaint(), changing the order, but I keep getting this:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: This function should be called while holding treeLock
at java.awt.Component.checkTreeLock(Component.java:1196)
at java.awt.Container.validateTree(Container.java:1682)
at nivel_2.formulario2.AceptarActionPerformed(formulario2.java:148)
at nivel_2.formulario2.access$100(formulario2.java:20)
at nivel_2.formulario2$2.actionPerformed(formulario2.java:93)
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:3311)
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)
I don't get any error at the source editor, and using any other method, the JFrame doesn't refresh. What can I do to make it work?
Pd.: the error appears just when this block of code executes.
Do not use Thread.sleep() as it will freeze your Swing application.
Instead you should use a javax.swing.Timer.
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.
I think I haven't given enough informaton, or I'm too noob (I don't know), so I'm gonna put here all the class that is giving me problems (It's a Jbutton), changed with the recomendations you have given me (still not working):
private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {
if(xy==true && Respuesta.getText().equals("verdadero"))
{
sound = java.applet.Applet.newAudioClip(getClass().getResource("/sonido/enter.wav"));
sound.play();
r1.setIcon(new ImageIcon(getClass().getResource("/imagenes2/escalera.png")));
r2.setVisible(true);
dialog.setText("<html>\n" +
"<font color='blue'><center><h4>¡BIEN HECHO!<br>ahora resuelve la siguiente<br>pista.</h4></center> </font>\n" +
"</html>");
x=100;
xy=false;
xz=true;
}
else if(xz==true && Respuesta.getText().equals("falso"))
{
r2.setIcon(new ImageIcon(getClass().getResource("/imagenes2/escalera.png")));
dialog.setText("<html>\n" +
"<font color='blue'><center><h4>¡GENIAL!<br>¡VAMOS A LA SIGUIENTE CÁMARA!</h4><h5>Haz click aquí</h5></center> </font>\n" +
"</html>");
x=2;
}
else if(xy==true || xz==true)
{
mm1.setVisible(true);
mm2.setVisible(true);
mm1.repaint();
mm2.repaint();
sound = java.applet.Applet.newAudioClip(getClass().getResource("/sonido/monster.wav"));
sound.play();
sound1 = java.applet.Applet.newAudioClip(getClass().getResource("/sonido/grito.wav"));
sound1.play();
Timer timer1= new Timer(4000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
timer1.start();
formulariogame over2=new formulariogame();
over2.setVisible(true);
this.dispose();
}
}
What I need, is that when timer1.starts(), the execution stops for 4 seconds, giving time for the program to refresh the image. If Timer method doesn't work for what I want, please give me another recommendation. I would thank you a lot if you could send me the corrected code.
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.
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").
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
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.