Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables to ActionListener in Java

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?

like image 381
Leo Jiang Avatar asked Jun 14 '12 16:06

Leo Jiang


2 Answers

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" ));
   }
});
like image 54
Robin Avatar answered Sep 21 '22 01:09

Robin


In addition to Hovercraft's answer, you should note that you're not forced to use anonymous classes for your listeners. The code of Hovercraft's answer is similar to the following one:

private class PageActionListener implements ActionListener {
    private int page;

    public PageActionListener(int page) {
        this.page = page;
    }

    public void actionPerformed(ActionEvent e) {
        setPage(page);
    }
}

...

for(int i = 0; i < 10; i++){
    button = new JButton(buttons[i]);
    button.addActionListener(new PageActionListener(i));
    menu.add(button);
}
like image 43
JB Nizet Avatar answered Sep 20 '22 01:09

JB Nizet