Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用自定义组件属性?_Java_User Interface - Fatal编程技术网

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

Java 如何使用自定义组件属性?,java,user-interface,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:55

如果我使用自定义组件属性,我在尝试用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);
}
}




下面的类是我检查组件的地方

/*
* 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                   
}
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装重新包装;
进口proyectoreloj.AlarmaInterfaz;
/**
*
*@作者阿马罗
*/
公共类NewJFrame扩展了javax.swing.JFrame{
/**
*创建新表单NewJFrame
*/
公共NewJFrame(){
初始化组件();
proyectoReloj2.start();
ProyectorObj2.setAlarmaInterfaz(新的AlarmaInterfaz()
{
@凌驾
public void ejectaarma()
{
System.out.println(“Esto es la alarma”);
}
});
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
proyectoReloj1=新建proyectoreloj.proyectoreloj();
proyectoReloj2=新建proyectoreloj.proyectoreloj();
proyectoReloj1.setText(“proyectoReloj1”);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
proyectoReloj2.setText(“proyectoReloj2”);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(149149149)
.addComponent(proyectorObj2、javax.swing.GroupLayout.PREFERRED\u SIZE、javax.swing.GroupLayout.DEFAULT\u SIZE、javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(178,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(131131131)
.addComponent(proyectorObj2、javax.swing.GroupLayout.PREFERRED\u SIZE、javax.swing.GroupLayout.DEFAULT\u SIZE、javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(155,简称最大值))
);
包装();
}//                         
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
公开募捐{
新建NewJFrame().setVisible(true);
}
});
}
//变量声明-不修改
私有proyectoreloj.proyectoreloj proyectoReloj1;
私人项目2;
//变量结束声明
}

ProyectoReloj.alarma
为空。您不能调用
ProyectoReloj.setAlarma
。您需要在启动计时器之前设置它,或者您应该在run方法中选中
getAlarm()==null

,您有以下代码:

        if((hora == getAlarma().getHora()) && (minutos == getAlarma().getMinutos()))
        {
            alarmaInterfaz.ejecutaAlarma();
        }
我猜getAlarma()将返回null(您不初始化该值),而getHora调用将导致NPE


此外,与每秒检查一次警报不同,您应该构建计时器,使其仅在警报关闭时唤醒(即从现在到警报关闭时间之间的计算毫秒)

问题的可能重复之处在于,我在AlarmaPanel类中设置了警报,该类警报是一个带有两个JTextField的JPanel,第一个是小时,第二个是分钟。我以为闹钟是在我按下thar JPanel中的“ok”时设置的,所以我不知道如何设置闹钟。
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                   
}
        if((hora == getAlarma().getHora()) && (minutos == getAlarma().getMinutos()))
        {
            alarmaInterfaz.ejecutaAlarma();
        }