简体   繁体   English

将变量传递给Java中的ActionListener

[英]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. 但是,变量i没有在ActionListener类的范围内定义。 How can I pass the variable? 如何传递变量?

In addition to Hovercraft's answer, you should note that you're not forced to use anonymous classes for your listeners. 除了Hovercraft的答案外,您还应该注意,您不会被迫对侦听器使用匿名类。 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);
}

A totally different approach would be to add a property to the button, and retrieve that property in your action listener. 完全不同的方法是向按钮添加属性,然后在动作侦听器中检索该属性。 Eg 例如

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

The variable i is in fact in the scope of the ActionListener, but since you're trying to use a local variable in an inner class, the variable must be final. 变量i 其实在ActionListener的范围,但因为你是试图一个内部类使用一个局部变量,该变量必须是最终决定。 So, you could use a final variable for this: 因此,您可以为此使用最终变量:

for(int i=0;i<10;i++){
    final int index = i;
    button=new JButton(buttons[i]);
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            setPage(index);
        }
    });
    menu.add(button);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM