Pass variables to ActionListener in Java

Leo Jiang picture Leo Jiang · Jun 14, 2012 · Viewed 31.7k times · Source

I have something like the code below:

    for(int i=0;i<10;i++){
        button=new JButton(buttons[i]);
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                setPage(i);
            }
        });
        menu.add(button);
    }

However, the variable i isn't defined in the scope of the ActionListener class. How can I pass the variable?

Answer

Robin picture Robin · Jun 14, 2012

A totally different approach would be to add a property to the button, and retrieve that property in your action listener. E.g.

button=new JButton(buttons[i]);
button.putClientProperty( "page", i );
button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
      setPage((Integer)((JButton)e.getSource()).getClientProperty( "page" ));
   }
});