Pass variables to ActionListener in Java

后端 未结 3 1669
庸人自扰
庸人自扰 2020-12-03 23:18

I have something like the code below:

    for(int i=0;i<10;i++){
        button=new JButton(buttons[i]);
        button.addActionListener(new ActionListen         


        
相关标签:
3条回答
  • 2020-12-03 23:57

    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. 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);
    }
    
    0 讨论(0)
  • 2020-12-04 00:06

    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);
    }
    
    0 讨论(0)
  • 2020-12-04 00:10

    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" ));
       }
    });
    
    0 讨论(0)
提交回复
热议问题