如何制作JButton的for循环?

时间:2015-10-18 17:36:49

标签: 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)
  }
}

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

2 个答案:

答案 0 :(得分:2)

for(int i = 0; i < 8; i++) {
    buttonLayout.add(new JButton());
}

这将向buttonLayout添加8个JButtons。

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

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

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

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);
}

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

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);
}

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

答案 1 :(得分:0)

首先初始化一组按钮。

JButton[] buttons = new JButton[8] // instead of having cat1, cat2 ... you have buttons[0], buttons[1] ...

然后执行for循环以初始化并添加每个按钮。

for (JButton button : buttons) {
    button = new JButton();
    buttonLayout.add(button);
}