开发者

How can I give a variable to an action listener?

I have a static variable partner in the class. And I want to set a value of these 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) {
            par开发者_StackOverflow社区tner = playerName;
        }
    });
    partnerSelectionPanel.add(option);
    group.add(option);
}

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


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. Originally I thought that you cannot make playerName final in the for loop, but in fact you can. If that wasn't the case, you would simply store playerName in additional final variable (final String pn = playerName) and used pn from actionPerformed.


Variable must be final to pass it into inner class.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜