我目前正在尝试创建一款战舰游戏。我遇到问题的部分是当我选择“随机”按钮时,我希望它将船只放置在网格的随机部分。
例如,航母将覆盖阵列内的 5 个 JButton。如何在数组中随机选择 5 个彼此相邻的 JButton?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.util.Random;
public class View
{
private JFrame frame;
private JPanel panel1;
private JPanel panel2;
private JButton grid1[][];
private JButton randomize;
private String[] alphabet = { "", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
private String[] numbers = { "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
public View()
{
configureFrame();
configurePanels();
configureComponents();
frame.setVisible(true);
}
private void configureFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 600);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
}
private void configurePanels()
{
panel1 = new JPanel();
panel1.setLayout(new GridLayout(11, 11));
frame.getContentPane().add(panel1, BorderLayout.WEST);
panel2 = new JPanel();
panel2.setSize(frame.getWidth(), frame.getHeight());
panel2.setLayout(null);
frame.getContentPane().add(panel2);
}
private void configureComponents()
{
grid1 = new JButton[11][11];
for(int i = 0; i < grid1.length; i++)
{
for(int j = 0; j < grid1[i].length; j++)
{
grid1[i][j] = new JButton();
panel1.add(grid1[i][j]);
}
}
我对 Java 很陌生,所以如果我没有任何意义,我提前道歉。
呼啦一阵风
相关分类