Re: ActionListener
Hello Art, you "top-posted" please don't do that. Top-posting
reorganised ...
Art Cummings wrote:
Knute Johnson wrote:
Art Cummings wrote:
I'm trying to understand how to invoke an ActionListener but
maintain a variable that will be available to another
ActionListener called "previous". The problem is how to have a
variable persists between calls. I want to populate the ArrayList
everytime the user hits next or previous and use my variable to
position it at the correct index.
[Code for two independent ActionListener classes omitted]
Make the variables instance or class variables.
class MyClass { final ArrayList list = new ArrayList();
list is visible to the entire class including subclasses.
Knute, i'm not sure i understand. I'm trying to make the index
variable availble to the other methods. The idea is that this index
can be used to either go forward or backward depending on which
ActionListener is called. Is there a way to do this with an interger
value? You may have already explained this and i'm too thick to see,
so please have patience.
If you posted a more complete example, we'd be able to suggest a better
way to organise the code.
class IndexView extends JPanel implements ActionListener {
private int index;
private static String PRIOR = "Previous", NEXT = "Next";
private JLabel indexLabel = new JLabel();
IndexView() {
JButton n = new JButton(NEXT);
n.addActionListener(this);
add(n);
JButton p = new JButton(PRIOR);
p.addActionListener(this);
add(p);
add (indexLabel);
}
// One actionlistener can service many buttons
actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals(PRIOR))
index--;
else if (command.equals(NEXT))
index++;
else
System.out.println("Unexpected command " + command);
indexLabel.setText("index = " + index);
}
// Maybe you need access to index in the class that
// instantiates IndexView?
public int getIndex() {
return index;
}
}
Untested. Batteries not included.