如何让我的网格填充所有单元格?
Posted
技术标签:
【中文标题】如何让我的网格填充所有单元格?【英文标题】:How can I make my grid populate all cells? 【发布时间】:2022-01-10 09:31:59 【问题描述】:我正在使用 for 循环随机填充一个 8x8 网格,其中包含两个不同的按钮。我有一组按钮实例,出于某种原因,它只给我每个按钮一个,而不用任何东西填充网格的其余部分。有什么建议吗? 我只包含了代码的 buildPanel 块,但我确实有单独的按钮类和 Game 类。我还完成了其余的代码。它还没有完全满足我的需要并且需要清理,但如果它可能有助于解决这个问题,我可以发布它。如果不写更多细节,我无法在问题中发布比这更多的代码,但我认为这是一个非常简单的问题。
private void buildPanel()
// Create labels to display the
treasuresLeftLabel = new JLabel("Treasures left: ");
treasuresFoundLabel = new JLabel("Treasures found: ");
triesLeftLabel = new JLabel("Tries left: ");
// Create text fields for each label
treasuresLeftTextField = new JTextField(2);
treasuresLeftTextField.setEditable(false);
treasuresLeftTextField.setText(String.valueOf(20-game.getTreasuresFound()));
treasuresFoundTextField = new JTextField(2);
treasuresFoundTextField.setEditable(false);
treasuresFoundTextField.setText(String.valueOf(game.getTreasuresFound()));
triesLeftTextField = new JTextField(2);
triesLeftTextField.setEditable(false);
triesLeftTextField.setText(String.valueOf(game.getTriesLeft()));
emptyButton = new EmptyButton();
emptyButton.addActionListener(new emptyButtonListener());
treasureButton = new TreasureButton();
treasureButton.addActionListener(new treasureButtonListener());
// new JPanel object referenced by panel
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JLabel("Treasure Hunt", JLabel.CENTER), BorderLayout.NORTH);
statsPanel = new JPanel();
statsPanel.setLayout(new GridLayout(3, 2));
statsPanel.add(treasuresLeftLabel);
statsPanel.add(treasuresLeftTextField);
statsPanel.add(treasuresFoundLabel);
statsPanel.add(treasuresFoundTextField);
statsPanel.add(triesLeftLabel);
statsPanel.add(triesLeftTextField);
panel.add(statsPanel, BorderLayout.WEST);
JButton[] buttons = new JButton[62];
for (int index = 0; index < 62; index++)
if (index < 20)
buttons[index] = treasureButton;
else
buttons[index] = emptyButton;
gameGridPanel = new JPanel();
gameGridPanel.setLayout(new GridLayout(8, 8));
// Generate a random number between 0 and 61
int randomNumber = new Random().nextInt(62);
for (int count = 0; count < 62; count++)
if (buttons[randomNumber] != null)
gameGridPanel.add(buttons[randomNumber]);
randomNumber = new Random().nextInt(62);
else
randomNumber = new Random().nextInt(62);
panel.add(gameGridPanel, BorderLayout.CENTER);
【问题讨论】:
【参考方案1】:每个按钮只给我一个
因为每个按钮只有一个实例:
for (int index = 0; index < 62; index++)
if (index < 20)
buttons[index] = treasureButton; // single instance
else
buttons[index] = emptyButton; // single instance
添加到数组时需要创建一个新实例。
for (int index = 0; index < 62; index++)
if (index < 20)
//buttons[index] = treasureButton;
buttons[index] = new TreasureButton();
else
//buttons[index] = emptyButton;
buttons[index] = new EmptyButton();
还有一种更简单的随机化按钮的方法是:
-
将按钮添加到
ArrayList
使用Collections.shuffle(...)
方法随机化按钮的顺序
遍历ArrayList
并将每个按钮添加到网格中
【讨论】:
以上是关于如何让我的网格填充所有单元格?的主要内容,如果未能解决你的问题,请参考以下文章