我目前正在尝试创建《战舰》游戏。我遇到的问题是,当我选择“随机化”按钮时,我希望它可以将飞船放置在网格的随机部分。
例如,运输船将覆盖阵列中的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]);
}
}
for(int i = 0; i < alphabet.length && i < numbers.length; i++)
{
grid1[0][i].setText(alphabet[i]);
grid1[i][0].setText(numbers[i]);
grid1[0][i].setFont(new Font("Tahoma", Font.BOLD, 19));
grid1[i][0].setFont(new Font("Tahoma", Font.BOLD, 19));
grid1[0][i].setEnabled(false);
grid1[i][0].setEnabled(false);
grid1[0][i].setBackground(Color.BLACK);
grid1[i][0].setBackground(Color.BLACK);
}
grid1[0][0].setBackground(Color.BLACK);
randomize = new JButton("Randomize");
randomize.setLocation(50, 65);
randomize.setSize(100, 50);
randomize.setFocusPainted(false);
randomize.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
/*
Want to randomly put the carrier on the grid somewhere
grid1[2][3].setBackground(Color.LIGHT_GRAY);
grid1[3][3].setBackground(Color.LIGHT_GRAY);
grid1[4][3].setBackground(Color.LIGHT_GRAY);
grid1[5][3].setBackground(Color.LIGHT_GRAY);
grid1[6][3].setBackground(Color.LIGHT_GRAY);
*/
}
});
panel2.add(randomize);
}
}
我对Java还是很陌生,所以如果我没有任何道理,我会提前道歉。
答案 0 :(得分:0)
如何在数组中随机选择5个彼此相邻的JButton?