0

I have this Java class where the if/else statement in actionPerformed doesn't work. if i remove the if statement and just put some statements(i.e show messgae dialog) the are invoked/executed successfully.

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);
}
}

not sure what the problem is !

I looked at some of the question here but none is similar.

Thanks for your help.

Ahmed
  • 413
  • 5
  • 9

2 Answers2

1

You're shadowing your variables...

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");

See how you've declared them twice. This means that the action source been passed to your actionPerformed method is not the same instance as the one your class has, so == won't work.

Remove the re-decelerations in your constructor

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

The problem is that you are redefining your button types inside of your constructor. So you are shadowing them and using the wrong ones in your ActionListener.

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

vs

    JButton carBtn = new JButton("Car");
    JButton vanBtn = new JButton("Van");
    JButton reset = new JButton("Reset");
WJS
  • 36,363
  • 4
  • 24
  • 39