How can I pass a variable to an action listener?

I have a static partner variable in the class. And I want to set the value of this variable whenever a radio button is pressed. This is the code I tried to use:

 for (String playerName: players) { option = new JRadioButton(playerName, false); option.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { partner = playerName; } }); partnerSelectionPanel.add(option); group.add(option); } 

The problem here is that actionPerformed does not see the playerName variable created in the loop. How to pass this variable to actionListener?

+4
source share
3 answers
 for (final String playerName: players) { option = new JRadioButton(playerName, false); option.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { partner = playerName; } }); partnerSelectionPanel.add(option); group.add(option); } 

Local variables passed to inner classes must be final. Initially, I thought that you cannot make playerName final in a for loop, but you can actually. If this were not the case, you would simply playerName in an additional final variable ( final String pn = playerName ) and use pn from actionPerformed .

+9
source

The variable must be final in order to pass it to the inner class.

+2
source
 JButton button = new JButton("test"); button.addActionListiner(new ActionForButton("test1","test2")); class ActionForButton implements ActionListener { String arg,arg2; ActionFroButton(String a,String b) { arg = a; arg2 = b; } @Override public void actionPerformed(ActionEvent e) { Sustem.out.println(arg + "--" + arg2); } } 
+1
source

Source: https://habr.com/ru/post/1304701/


All Articles