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部分。謝謝!如何製作JButton的循環?
非常感謝,完美的工作,但我也試圖添加一個圖像到所有的按鈕。這是我試過的,但沒有奏效。 –
@cyderickt ArrayList buttonList = new ArrayList (); (int i = 0; i <42; i ++){ \t \t { \t \t ImageIcon square = new ImageIcon(「square.jpg」); \t \t \t JButton squares = new JButton(square); \t \t buttonList.add(squares); \t \t buttonLayout.add(squares); \t \t} –
有關如何添加圖像的詳細信息,請參閱我的編輯。 – CydrickT