0

I have a problem when trying to create an event in java if I use custom component properties. I created a digital clock and I have an alarm which I would like to throw an event but when I run my program, it doesn't because of an exception:

Exception in thread "Timer-0" java.lang.NullPointerException
at proyectoreloj.ProyectoReloj$1.run(ProyectoReloj.java:73)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

My code is:

public class ProyectoReloj extends JLabel implements Serializable
{

int hora, minutos;
boolean formato24h = false;
private Alarma alarma;
private AlarmaInterfaz alarmaInterfaz;

public ProyectoReloj()
{}


public Alarma getAlarma() {
    return alarma;
}


public void setAlarma(Alarma alarma) {
    this.alarma = alarma;
}


public boolean isFormato24h() {
    return formato24h;
}

public void setFormato24h(boolean formato24h) {
    this.formato24h = formato24h;
}


public void setAlarmaInterfaz(AlarmaInterfaz alarmaInterfaz) {
    this.alarmaInterfaz = alarmaInterfaz;
}


public void start()
{
    Timer timer = new Timer();
    timer.schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            Calendar calendario = Calendar.getInstance();
            hora = Calendar.HOUR;
            minutos = Calendar.MINUTES;
            if(formato24h == false)
            {

                SimpleDateFormat formato = new SimpleDateFormat("hh:mm:ss");
                setText(formato.format(calendario.getTime()));
            }
            else
            {
                SimpleDateFormat formato = new SimpleDateFormat("HH:mm:ss");
                setText(formato.format(calendario.getTime()));
            }

            if((hora == getAlarma().getHora()) && (minutos == getAlarma().getMinutos()))
            {
                alarmaInterfaz.ejecutaAlarma();
            }
        }
    },0,1000);
}
}

public class Alarma implements Serializable
{

private int hora = 8;
private int minutos = 26;


public int getHora() {
    return hora;
}

public int getMinutos() {
    return minutos;
}


public Alarma(int hora, int minutos)
{
    this.hora = hora;
    this.minutos = minutos;
}
}

public interface AlarmaInterfaz
{
    void ejecutaAlarma();
}

public class AlarmaPanel extends javax.swing.JPanel {

/**
 * Creates new form AlarmaPanel
 */
public AlarmaPanel() {
    initComponents();
}

public Alarma getAlarm()
{
    if(!horasField.getText().equalsIgnoreCase("") && minutosField.getText().equalsIgnoreCase(""))
    {
        int horas = Integer.parseInt(horasField.getText());
        int minutos = Integer.parseInt(minutosField.getText());
        return new Alarma(horas, minutos);
    }
    return null;
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    horasField = new javax.swing.JTextField();
    minutosField = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    horasField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            horasFieldActionPerformed(evt);
        }
    });

    jLabel1.setText(":");

    jLabel2.setText("ALARMA");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(horasField, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(minutosField, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(55, 55, 55))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(horasField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(minutosField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1)
                .addComponent(jLabel2))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
}// </editor-fold>                        

private void horasFieldActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
}                                          


// Variables declaration - do not modify                     
private javax.swing.JTextField horasField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField minutosField;
// End of variables declaration                   
}

public class RelojPropertyEditorSupport extends PropertyEditorSupport
{
private AlarmaPanel alarmaPanel = new AlarmaPanel();

@Override
public boolean supportsCustomEditor()
{
    return true;
}

@Override
public Component getCustomEditor()
{
    return alarmaPanel;
}

@Override
public Object getValue()
{
    return alarmaPanel.getAlarm();
}


@Override
public String getJavaInitializationString()
{
    int horas = alarmaPanel.getAlarm().getHora();
    int minutos = alarmaPanel.getAlarm().getMinutos();
    return "new proyectoreloj.Alarma("+horas+","+ minutos+")";
}
}

The following class is where I check my component

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package relojprueba;

import proyectoreloj.AlarmaInterfaz;

/**
 *
 * @author Amaro
 */
public class NewJFrame extends javax.swing.JFrame {

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
    proyectoReloj2.start();
    proyectoReloj2.setAlarmaInterfaz(new AlarmaInterfaz()
    {
        @Override
        public void ejecutaAlarma()
        {
            System.out.println("Esto es la alarma");                    
        }
    });
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    proyectoReloj1 = new proyectoreloj.ProyectoReloj();
    proyectoReloj2 = new proyectoreloj.ProyectoReloj();

    proyectoReloj1.setText("proyectoReloj1");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    proyectoReloj2.setText("proyectoReloj2");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(149, 149, 149)
            .addComponent(proyectoReloj2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(178, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(131, 131, 131)
            .addComponent(proyectoReloj2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(155, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private proyectoreloj.ProyectoReloj proyectoReloj1;
private proyectoreloj.ProyectoReloj proyectoReloj2;
// End of variables declaration                   
}
Amaro88
  • 1
  • 2
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå Dec 04 '14 at 16:16

2 Answers2

0

ProyectoReloj.alarma is null. you dont call ProyectoReloj.setAlarma. you need to set it before start the timer or you should check getAlarm() == null

Adem
  • 9,402
  • 9
  • 43
  • 58
0

In your run method, you have this code:

        if((hora == getAlarma().getHora()) && (minutos == getAlarma().getMinutos()))
        {
            alarmaInterfaz.ejecutaAlarma();
        }

I would guess that getAlarma() is returning null (you don't initialize the value) and the getHora call is causing the NPE.

Also, rather than checking the alarm every second, you should build your timer so that it only wakes up when the alarm should go off (ie calc milliseconds between now and alarm goes off time)

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • The problem is that I set the alarm in class AlarmaPanel witch is a JPanel with two JTextField, the first is for the hour and the second is for the minutes. I thought that the alarm was setted when I press "ok" in thar JPanel, so I don't know how can I set the Alarm. – Amaro88 Dec 04 '14 at 16:40