2013-05-01 81 views
0

我有一个动作侦听器,如果变量值为null,我想取消当前迭代。有没有一种方法可以让ActionListener取消?

public class ValidateListener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     myCalendarKey mCal = Project5.verifyDate(month+"/"+day+"/"+year); //month day and year are defined, just not in this code display. 

     if (mCal == null) e.cancel(); //I need something to cancel the current ActionEvent if this returns true. 

     /* A lot more code down here that only works if mCal is defined */ 
    } 
} 

我想我可以用一个if-else语句,并如果mCal != null它做的一切,如果mCal == null什么也不做,但有一个更好的方式来做到这一点?

+0

*“有没有更好的方法来做到这一点?”*这种方式没有错。或者,当值为空时禁用控制或“操作” - 那么事件不会首先被触发! – 2013-05-01 15:22:34

+0

@Andrew上面的方法并没有取消行动(这似乎是要求 - 虽然我可能是错的)。它只是停止处理这个特定的事件监听器。 – StuPointerException 2013-05-01 15:38:02

+0

@StuPointerException *“虽然我可能是错的”*是的,你可能,我不是特别感兴趣的人谁不是OP的投机。 – 2013-05-01 15:40:29

回答

0

试试这个:

@Override 
public void actionPerformed(ActionEvent e) { 
    myCalendarKey mCal = Project5.verifyDate(month+"/"+day+"/"+year); 
    if(mCal != null) { 
     /* A lot more code down here that only works if mCal is defined */ 


    } 
} 
+0

这会停止动作侦听器的逻辑,但不会取消事件(我认为这是要求)。 – StuPointerException 2013-05-01 15:29:04

0

我不会说这是更好,但你也可以这样做。

@Override 
public void actionPerformed(ActionEvent e) { 
    myCalendarKey mCal = Project5.verifyDate(month+"/"+day+"/"+year); 
    if(mCal != null) return; 
    ... 
} 
相关问题