gpt4 book ai didi

java - 我有一个 JButton 的 2D 数组,但似乎只有一个 JButton 添加到我的面板中

转载 作者:行者123 更新时间:2023-12-01 23:24:13 25 4
gpt4 key购买 nike

我试图让我的 JPanel 在 10 x 10 网格中包含 100 个 Jbutton,但是当我运行代码时,只出现 1 个大按钮。我在下面发布了我的代码,所有导入已被删除以节省空间,所有必要的导入都在项目中,但此处未显示。

这是我的“SnowballFight”类(class):

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

最佳答案

frame.add(game[row][col]);

您确实意识到 JFrame 的默认布局是 BorderLayout 对吗?并且只有一个组件可以出现在 BorderLayout 的任何一个区域中?请改用 GridLayout

关于java - 我有一个 JButton 的 2D 数组,但似乎只有一个 JButton 添加到我的面板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20258477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com