如何使用自定义组件属性?

时间:2014-12-04 16:15:00

标签: java user-interface

如果我使用自定义组件属性,尝试在java中创建事件时遇到问题。我创建了一个数字时钟,我有一个警报,我想要举办一个活动,但是当我运行我的程序时,它没有因为一个例外:

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)

我的代码是:

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+")";
}
}

以下课程是我检查组件的地方

/*
* 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                   
}

2 个答案:

答案 0 :(得分:0)

ProyectoReloj.alarma为空。你不打电话给ProyectoReloj.setAlarma。你需要在启动计时器之前设置它,或者你应该检查getAlarm() == null

答案 1 :(得分:0)

在您的run方法中,您有以下代码:

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

我猜想getAlarma()返回null(你没有初始化值)并且getHora调用导致了NPE。

此外,不是每秒检查一次警报,而是应该建立你的计时器,以便它只在警报响起时唤醒(即从现在到警报之间的毫秒数,停止时间)

相关问题