0

This program is supposed to save the button value "ab" to the ArrayList whenever the button is pressed, but the if command seems to never work, I tried removing it and seeing if it works, it does and the ArrayList is updated with the new value. So if I pressed the button or not when it appears in the J Windows, nothing happens.

This program later on saves the array to a file, so basically nothing is saved if the if is there and I clicked as many times I wanted, but if the if loop in this one goes then it works

 public void actionPerformed(ActionEvent a) 
    {
        ArrayList<String> aList = new ArrayList<String>();
            if (a.getActionCommand() == "ab")
                aList.add("ab");
    }

So if this was done it world print out and aList would be filled with ab in the zero index :

public void actionPerformed(ActionEvent a) 
{
         ArrayList<String> aList = new ArrayList<String>();
            aList.add("ab");
}
  • You're not returning that list so it gets destroyed after you leave actionPerformed method. – Keammoort Dec 14 '15 at 13:45
  • The array is sent to the file inside the method, so I don't leave the method empty handed. I removed the if (a.getActionCommand() -- "ab" ), and it works perfectly, I just need it to work with the loop now – MoodyKhader Dec 14 '15 at 13:48

2 Answers2

0

Firstly, aList is local variable and it'll be removed on the exit of the method.

Secondly:

a.getActionCommand() == "ab"

You must compare String objects using equals method:

a.getActionCommand().equals("ab")

or

"ab".equals(a.getActionCommand()) //hack for prevention null reference after a.getActionCommand()

There is reference comparison in your example, but using equals you'll be compare objects, not references.

dgabriel
  • 267
  • 2
  • 15
0

Your list only exists in the scope of the method. In order to work with it from the "outside" you should use it as a instance variable.

For example:

public class A implements ActionListener {
    private final List<String> aList;

    public A() {
        aList = new ArrayList<String>();
    }

    ...

    public void actionPerformed(ActionEvent a) 
    {
        if (a.getActionCommand().equals("ab")) {
            aList.add("ab");
        }
    }
}
QBrute
  • 4,405
  • 6
  • 34
  • 40
  • What error? You never mentioned one. Also have you tried to compare the action command with `equals()` as i've written it in the code? – QBrute Dec 14 '15 at 15:11
  • I meant, still the same issue, and I got the == from the oracle in java file from their website. So nothing happened, still the file is not filling up with array values. I want it to be local to that class, because in that same class it prints to a file. Like in the action performed file, there is an if statement that if the button enter is pressed it would print it to the file – MoodyKhader Dec 14 '15 at 15:19