2015-10-18 58 views
-1
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的循環?

回答

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

這將爲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); 
} 

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

當然,根據編輯的路徑你需要。請注意,路徑可以是相對的,意思是基於程序的位置。

+0

非常感謝,完美的工作,但我也試圖添加一個圖像到所有的按鈕。這是我試過的,但沒有奏效。 –

+0

@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} –

+0

有關如何添加圖像的詳細信息,請參閱我的編輯。 – CydrickT

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