如何在 Java WindowBuilder 中以编程方式添加按钮

How to add buttons programmatically in Java WindowBuilder

我正在为大学的一个科目制作游戏(扫雷)。

我关注的是第一层,它有 7 行和 10 列。所以我想以某种方式添加,以编程方式为每个方块添加按钮。因为在这种情况下,我需要添加 70 个按钮 (7x10)。

这是为两个按钮生成 WindowBuilder 编辑器的代码。

// buttons
private JButton button;
private JButton button_1;

public VTableroN1() {   
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.WHITE);
    frame.setBounds(100, 100, 640, 480);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new MigLayout("", "[10%][10%][10%][10%][10%][10%][10%][10%][10%][10%]", "[14.28%][14.28%][14.28%][14.28%][14.28%][14.28%][14.28%]"));
    // buttons 
    frame.getContentPane().add(getButton(), "cell 0 0,grow");
    frame.getContentPane().add(getButton_1(), "cell 1 0,grow");
    frame.setVisible(true);
}

// buttons
private JButton getButton() {
    if (button == null) {
        button = new JButton("");
    }
    return button;
}
private JButton getButton_1() {
    if (button_1 == null) {
        button_1 = new JButton("");
    }
    return button_1;
}

我的问题是,如何在不逐一添加的情况下以迭代方式添加 70 个按钮?

我想这是一个愚蠢的问题,但我还没有找到好的解决方案。我在 Whosebug 中找不到任何关于此的信息,除了 Android 之外只有类似的问题,但这与我认为的无关。

提前致谢,如果您需要我粘贴更多代码,请告诉我。我想我只粘贴了相关代码。

完整的工作代码如下:

private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.WHITE);
    frame.setBounds(100, 100, 640, 480);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new MigLayout("", "[10%][10%][10%][10%][10%][10%][10%][10%][10%][10%]", "[14.28%][14.28%][14.28%][14.28%][14.28%][14.28%][14.28%]"));
    frame.setVisible(true);
    for (int row = 0; row<7; row++) {
        for (int col = 0; col<10; col++) {
            JButton b = new JButton();
            frame.getContentPane().add(b, "cell "+ col +" "+ row +",grow");
            // click method
            frame.getContentPane().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent arg0) {
                    // code
                }
            });
        }
    }
}

重要的是

for (int row = 0; row<7; row++) {
    for (int col = 0; col<10; col++) {
        JButton b = new JButton();
        frame.getContentPane().add(b, "cell "+ col +" "+ row +",grow");
    }
}