我可以使用逻辑OR运算符来测试if语句中的两个条件吗?

时间:2014-01-08 02:08:42

标签: java swing user-interface if-statement awt

我有一个开始按钮和一个弹出菜单选项,可以执行相同的操作。是否可以在同一个if语句中测试两个按钮,或者我是否必须为它们编写两个单独的if语句?

我想做这样的事情:

public void actionPerformed(ActionEvent e){

            // The start button and the popup start menu option
            if (e.getSource() == start)||(e.getSource() == startPopup){
                new Thread() {
                    @Override 
                    public void run() {
                        GreenhouseControls.startMeUp();
                    }
                }.start();

1 个答案:

答案 0 :(得分:6)

这里唯一的问题是括号。 if语句的格式为:

if (condition)
   body

目前你已经

if (condition1) || (condition2)
   body

无效。你只想要:

if (e.getSource() == start || e.getSource() == startPopup)

或者可能提取出共性:

Object source = e.getSource();
if (source == start || source == startPopup)

如果您真的需要,可以添加额外的括号:

Object source = e.getSource();
if ((source == start) || (source == startPopup))

...但是括号中必须只有一个整体表达式。