gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:49:07 24 4
gpt4 key购买 nike

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

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

First two grey boxes are two buttons...这是为两个按钮生成 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 个按钮,而不需要逐一执行此操作?

我想这是一个愚蠢的问题,但我还没有找到一个好的解决方案。我在 StackOverflow 中找不到任何关于此问题的信息,只有类似的问题,但针对 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");
}
}

关于java - 如何在 Java WindowBuilder 中以编程方式添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com