if/else actionPerformed 函数中的语句不起作用

if/else statment in actionPerformed function not working

我有这个 Java class,其中 actionPerformed 中的 if/else 语句不起作用。如果我删除 if 语句并仅放置一些语句(即显示消息对话框),则 invoked/executed 成功。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CarsAndVans extends JFrame implements ActionListener {


final JButton carBtn = new JButton("Car");
final JButton vanBtn = new JButton("Van");
final JButton reset = new JButton("Reset");
JTextField carTex = new JTextField(10);
JTextField vanTex = new JTextField(10);
int cars = 0, vans = 0;

CarsAndVans() {
    setLayout(new FlowLayout());
    setSize(400, 300);
    setTitle("Cars and Vans Applet");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);

    JButton carBtn = new JButton("Car");
    JButton vanBtn = new JButton("Van");
    JButton reset = new JButton("Reset");
    JTextField carTex = new JTextField(10);
    carTex.setEditable(false);
    JTextField vanTex = new JTextField(10);
    vanTex.setEditable(false);
    int cars = 0, vans = 0;

    carTex.setEditable(false);
    vanTex.setEditable(false);

    add(new Label("Cars"));
    add(carTex);
    add(new Label("Van:"));
    add(vanTex);
    add( carBtn);
    add( vanBtn);
    add( reset);

    carBtn.addActionListener(this);
    vanBtn.addActionListener(this);
    reset.addActionListener(this);


}
@Override
public void actionPerformed(ActionEvent actionEvent) {

    if (actionEvent.getSource() == carBtn){
        cars++;
    } else if (actionEvent.getSource() == vanBtn) {
        vans++;
    } else if ((actionEvent.getSource() == reset)) {
        vans = 0;
        cars = 0;
    }
    carTex.setText(""+cars);
    vanTex.setText(""+vans);
}
}

不确定是什么问题!

我在这里看了一些问题,但 none 是相似的。

感谢您的帮助。

您正在隐藏变量...

final JButton carBtn = new JButton("Car");
final JButton vanBtn = new JButton("Van");
final JButton reset = new JButton("Reset");

CarsAndVans() {
    //...
    JButton carBtn = new JButton("Car");
    JButton vanBtn = new JButton("Van");
    JButton reset = new JButton("Reset");

看看你是如何声明它们两次的。这意味着传递给您的 actionPerformed 方法的操作源与您的 class 方法的实例不同,因此 == 将不起作用。

删除构造函数中的重新减速

问题是您正在构造函数中重新定义按钮类型。所以你在隐藏它们并在你的 ActionListener 中使用错误的。

final JButton carBtn = new JButton("Car");
final JButton vanBtn = new JButton("Van");
final JButton reset = new JButton("Reset");

    JButton carBtn = new JButton("Car");
    JButton vanBtn = new JButton("Van");
    JButton reset = new JButton("Reset");