Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...