Pass variables to ActionListener in Java

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

Leave a Comment