如何制作 JButton 的 for 循环?

Edd*_*ite 1 java jbutton

public class BoardView extends JFrame
 {

private JButton board [][];

private GameBoard gameboard;

public static JButton cat1 = new JButton();
public static JButton cat2 = new JButton();
public static JButton car1 = new JButton();
public static JButton car2 = new JButton();
public static JButton dog1 = new JButton();
public static JButton dog2 = new JButton();
public static JButton bike1 = new JButton();
public static JButton bike2 = new JButton();

public BoardView()
{
    Container buttonLayout;
    /**
     * Exits the program when closed is clicked
     */
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /**
     * Sets the title for the Game
     */
    this.setTitle("Memory Of Humanity Game");
    /**
     * Sets the size for the JFrame
     */
    this.setSize(800, 600);
    /**
     * Makes the Pane into a Grid Layout so the Buttons 
     * Line up
     */
    buttonLayout = getContentPane();
    buttonLayout.setLayout(new GridLayout(7, 6));
    /**
     * This adds each JButton to the Pane of the Game
     */
    buttonLayout.add(cat1);
    buttonLayout.add(cat2);
    buttonLayout.add(car1);
    buttonLayout.add(car2);
    buttonLayout.add(dog1);
    buttonLayout.add(dog2);
    buttonLayout.add(bike1);
    buttonLayout.add(bike2)
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,我不必像这样一一添加每个 JButton,而是如何创建一个 for 循环来自动为我执行此操作?我在互联网上看到了一些,但是我不明白如何循环 JButton 的 .add 部分。谢谢你!

Gam*_*ega 5

for(int i = 0; i < 8; i++) {
    buttonLayout.add(new JButton());
}
Run Code Online (Sandbox Code Playgroud)

这将向 ButtonLayout 添加 8 个 JButton。

如果您稍后需要访问它们(您可能会这样做),您可能需要使用以下命令:

List<JButton> buttonList = new ArrayList<JButton>();
for(int i = 0; i < 8; i++) {
    JButton button = new JButton();
    buttonList.add(button);
    buttonLayout.add(button);
}
Run Code Online (Sandbox Code Playgroud)

如果您想向所有按钮添加单个图像:

for(int i = 0; i < 8; i++) {
    ImageIcon image = new ImageIcon("C:/path/to/your/image.jpg");
    JButton button = new JButton(image);
    buttonList.add(button);
}
Run Code Online (Sandbox Code Playgroud)

如果您想向按钮添加不同的图像:

String[] paths = {"C:/1.jpg", "C:/2.jpg", "C:/3.jpg", "C:/4.jpg", "C:/5.jpg", "C:/6.jpg", "C:/7.jpg", "C:/8.jpg"};
for(int i = 0; i < 8; i++) {
    ImageIcon image = new ImageIcon(paths[i]);
    JButton button = new JButton(image);
    buttonList.add(button);
}
Run Code Online (Sandbox Code Playgroud)

当然,根据您的需要编辑路径。请注意,路径可以是相对的,即基于程序的位置。