我試圖讓我的JPanel在10乘10的網格中有100個Jbuttons,但是當我運行我的代碼時只有1個大按鈕出現。我發佈了我的代碼,下面所有的導入都被刪除以節省空間,所有必要的導入都在項目中,但這裏沒有顯示。我有一個JButtons的二維數組,但它似乎只有一個JButton被添加到我的面板
這裏是我的 「打雪仗」 類:
package snowballfight;
public class SnowballFight extends JFrame implements ActionListener{
private JTextField display = new JTextField("Welcome to the SnowBall fight!");
/**
* @param args the command line arguments
*/
public SnowballFight(){
setLayout(new BorderLayout(1,2));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(10, 10));
display.setHorizontalAlignment(JButton.CENTER);
display.setEditable(false);
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SnowballFight frame = new SnowballFight();
GameBoard game = new GameBoard(frame);
}
public void actionPerformed(ActionEvent event) {
}
}
和我的 「遊戲鍵盤」 類:
package snowballfight;
public class GameBoard extends JFrame implements ActionListener{
private JButton[][] game = new JButton[10][10];
private JTextField display = new JTextField("Welcome to the SnowBall fight!");
private Opponent[] opponents = new Opponent[4];
public GameBoard(SnowballFight frame){
for (int row = 0; row < game.length; row++) {
for (int col = 0; col < game[row].length; col++) {
game[row][col] = new JButton();
game[row][col].setBackground(Color.gray);
game[row][col].addActionListener(this);
frame.add(game[row][col]);
}
}
frame.setTitle("Snowball Fight");
frame.setSize(200, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public boolean isGameOver(){
for (int opponent = 0; opponent < opponents.length; opponent++) {
if(opponents[opponent].isSoaked() == false){
return false;
}
}
return true;
}
public void actionPerformed(ActionEvent event) {
}
}
新遊戲鍵盤類:
public GameBoard(SnowballFight frame){
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(10, 10));
for (int row = 0; row < game.length; row++) {
for (int col = 0; col < game[row].length; col++) {
game[row][col] = new JButton();
game[row][col].setBackground(Color.gray);
game[row][col].addActionListener(this);
panel.add(game[row][col]);
}
}
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
frame.setTitle("Snowball Fight");
frame.setSize(200, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
*「節省空間所有必需的進口都在項目中。」* 1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)請參閱[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/a/9554657/418556) –