【发布时间】:2013-12-14 00:57:21
【问题描述】:
我试图让我的 JPanel 在 10 x 10 的网格中拥有 100 个 Jbutton,但是当我运行我的代码时,只出现了 1 个大按钮。我在下面发布了我的代码,所有导入已被删除以节省空间所有必要的导入都在项目中,但此处未显示。
这是我的“SnowballFight”课程:
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) {
}
}
还有我的“GameBoard”课:
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) {
}
}
新的 GameBoard 类:
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。 2) 见The Use of Multiple JFrames, Good/Bad Practice?
标签: java swing awt jbutton layout-manager