1
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]在动作监听器中访问它。我怎样才能做到这一点???

4

2 回答 2

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

        }
于 2013-06-15T18:20:50.160 回答
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"); 
    }
});
于 2013-06-15T18:11:05.210 回答