这是我的代码,我想知道每次单击已存在的按钮到实例框架时是否可以在网格布局中添加新按钮。
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){
}
}
}
答案 0 :(得分: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++;
}
}
}