有没有办法让ActionListener取消?

时间:2013-05-01 15:08:30

标签: java awt actionlistener

我有一个动作监听器,如果变量值为null,我想取消当前的迭代。

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则不执行任何操作,但有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是:

e.consume()

这会消耗这个事件: http://docs.oracle.com/javase/6/docs/api/java/awt/AWTEvent.html#consume()

答案 1 :(得分: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 */


    }
 }

答案 2 :(得分:0)

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

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