Java 有没有办法让ActionListener取消?
我有一个动作监听器,如果变量值为Java 有没有办法让ActionListener取消?,java,awt,actionlistener,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 ar
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,则不执行任何操作,但有更好的方法吗?尝试以下方法:
@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 */
}
}
我想你要找的是:
e.consume()
这将消耗事件:
我不认为这样更好,但你也可以这样做
@Override
public void actionPerformed(ActionEvent e) {
myCalendarKey mCal = Project5.verifyDate(month+"/"+day+"/"+year);
if(mCal != null) return;
...
}
“有更好的方法吗?”这种方法没有错。或者,当值为
null
时,禁用控件或操作
——则不会首先触发事件@Andrew上述方法并没有取消操作(这似乎是必要的——尽管我可能错了)。它只是停止了对这个特定事件侦听器的处理。“我对那些不是OP的人的推测并不特别感兴趣”-与您一起工作一定很愉快。不能保证您的ActionListener将是第一个调用的ActionListener。这会停止action listener的逻辑,但不会取消该事件(我认为这是要求)。但它受到保护--