Search code examples
javawindowsswinguser-interfacejbutton

action on jbutton press


I can't figure out how to make the following code work. When you press a jbutton I want it to run the following code. My problem is that the ArrayList list is located in the main and I don't know how to pass it into this method provided to me by the GUI builder so that, that actionperformed method will know what list is and return an ArrayList back to the main to replace it with the new changes.

btnNewButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            Student temp;

            Picker pick = new Picker(list);
            temp = pick.randomNoReplace();  //replace randomNoReplace() with radio button choice
            list.remove(temp);              //the next line must be temp.increaseScore() or temp.decreaseScore() or neither

            list.add(temp);
        }
}

Solution

  • What you are looking for is something like this:

    class Foo {
        private ArrayList<Student> list;
        ...
    

    This will declare list as an ArrayList of Students as an instance variable so that each object of this class can access list from any instance method. Just be sure to instantiate list before using it, preferably inside your constructor doing something like this:

    list = new ArrayList<Student>();