Wil*_*aan 5 java arrays swing jpanel jbutton
我想动态添加按钮数组.我试过这样的:
this.pack();
Panel panel = new Panel();
panel.setLayout(new FlowLayout());
this.add(panel);
panel.setVisible(true);
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
JButton b = new JButton(i+"");
b.setSize(30, 30);
b.setLocation(i * 30, j * 30);
panel.add(b);
b.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
但没有得到任何东西,我犯了什么错误?
我有jFrame类"选择",我有一个按钮,当我按下按钮时,这应该发生:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
structure.Setting s = new Setting(8, 8, 3, 1, 1);
Game g = new Game();
g.setSetting(s);
this.dispose();
g.show();
}
Run Code Online (Sandbox Code Playgroud)
然后我去了函数setSetting的Game类(也是jFrame类),它是这样的:
void setSetting(Setting s) {
this.setting = s;
structure.Game game = new structure.Game(setting);
JPanel panel = new JPanel(new GridLayout(5, 5, 4, 4));
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
JButton b = new JButton(String.valueOf(i));
panel.add(b);
}
}
add(panel);
pack();
setVisible(true);
}
structure.Setting setting;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用GridLayout添加相等高度/宽度的按钮:

public class Game extends JFrame {
private JPanel panel;
public Game(int rows,int cols,int hgap,int vgap){
panel=new JPanel(new GridLayout(rows, cols, hgap, vgap));
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=cols;j++)
{
JButton btn=new JButton(String.valueOf(i));
panel.add(btn);
}
}
add(panel);
pack();
setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
按钮处理程序中的代码应该是:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Game g = new Game(5,5,3,3);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以Setting通过Game构造函数传递对象引用(当您可以动态添加小部件时)而不是调用setSetting方法。
| 归档时间: |
|
| 查看次数: |
14892 次 |
| 最近记录: |