没有引用actionListener()中通过数组创建的按钮

时间:2013-06-15 18:08:07

标签: java

public class buttonInitialization extends JFrame {

public JButton[] button;

public buttonInitialization() {
    setLayout(new FlowLayout());    

    JButton[] button = new JButton[2];

    button[0] = new JButton("");
    button[0].setText("dsadsa");
    button[0].addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

                button[0].setText("dsaadsdsa"); 
        }

我无法在动作侦听器中访问此button[0]。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

制作button变量final

final JButton[] button = new JButton[2];

这是一个要求,因为匿名内部类(如new ActionListener())只有在final时才能访问外部类变量。

编辑我尝试编译并且可以正常工作。再来一次:

final JButton[] button = new JButton[2];

button[0] = new JButton("");
button[0].setText("dsadsa");
button[0].addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
            button[0].setText("dsaadsdsa"); 
    }
});

答案 1 :(得分:0)

     public class buttonInitialization extends JFrame {

            public JButton[] button;

        public buttonInitialization() {
            setLayout(new FlowLayout());    

            JButton[] button = new JButton[2];

            button[0] = new JButton("");
            button[0].setText("dsadsa");
            for(int i = 0; i< button.length; ++i)
                 button[i].addActionListener(new MyActionListener(button[i]));
        }

        private class MyActionListener implements ActionListener
        {
           private JButton button;

           public MyActionListener(JButton button)
           {
               this.button = button;
           }
              @Override
                    public void actionPerformed(ActionEvent arg0) {

                            this.button.setText("dsaadsdsa"); 
                    }

        }