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

标签 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();

最佳答案

这里唯一的问题是括号。 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))

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

关于java - 我可以使用逻辑或运算符来测试 if 语句中的两个条件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985732/

相关文章:

java - 根据结果​​将输出数据格式化为表格

java - 具有共享主键的 OneToOne 关系生成 n+1 个选择;任何解决方法?

java - 在按钮单击时添加 JTextFields

java - 根据最新的 KeyStroke 填充 JTextField

java - 如何检查 JPassword 字段是否为空

android - 二态按钮 : Show current state or next state?

java - 基本身份验证后 Spring Security 抛出 403

java - jackson 无效定义异常 : Cannot construct instance because no default no-arguments constructor found

java - 无法在 JPanel 中画线

Qt 设计师 : How to add widget to a layout in the designer when the layout appears infinitely thin?