0

这是我的代码,我想知道每次单击实例框架中的现有按钮之一时是否可以将新按钮添加到网格布局中。

public class Board {

        public static void main(String[] args) {
            JButton[] button = new JButton[40];
            int i = 0;
            JFrame frame = new JFrame();
            frame.setLayout(new GridLayout(20, 20, 15, 15));
            while (i < 40) {
                button[i] = new JButton("button" + i);
                button[i].addActionListener(new Action());
                frame.add(button[i]); 
                i++;
            }
            frame.setSize(700, 700);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }

        static class Action implements ActionListener{
            @Override
            public void actionPerformed (ActionEvent e){


            }
        }
    }
4

1 回答 1

3

解决方案相当简单。

你需要做的是思考问题。首先,您有一堆static确实不是必需的参考资料,并且给您带来的好处很少。

现在,说了这么多。您Action需要一些方法来知道在哪里添加按钮。为了做到这一点,Action需要引用要添加按钮的容器...

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Board {

    public static void main(String[] args) {
        new Board();
    }

    public Board() {
        JButton[] button = new JButton[40];
        int i = 0;
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(20, 20, 15, 15));
        Action action = new Action(frame);
        while (i < 40) {
            button[i] = createButton(i);
            button[i].addActionListener(action);
            frame.add(button[i]);
            i++;
        }
        action.setCount(i);
        frame.setSize(700, 700);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public JButton createButton(int index) {

        return new JButton("button" + index);

    }

    public class Action implements ActionListener {

        private JFrame frame;
        private int count;

        public Action(JFrame frame) {
            this.frame = frame;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton btn = createButton(count);
            btn.addActionListener(this);
            frame.add(btn);
            frame.revalidate();
            count++;
        }
    }
}
于 2013-03-21T00:01:53.277 回答