我正在尝试制作战舰游戏,我控制着棋盘。如何创建一个允许每个按钮返回位置的数组。用于存放船舶和命中物。我想制作每个按钮,但我不知道该怎么做。
答案 0 :(得分:2)
您可以扩展按钮类:
public class BattleShipButton extends JButton {
private Coordinate coords;
public BattleShipButton(Coordinates coords) {
this.coords = coords;
setPreferredSize(new Dimension(20, 20));
}
public Coordinates getCoordinates() {
return coords;
}
}
然后,您可以在循环中实例化按钮并传入正确的坐标。
BattleShipButton[][] buttons = new BattleShipButton[boardWidth][boardHeight];
for(int i = (int)'a'; i < boardWidth; i++){
for(int j = 0; j < boardHeight; j++) {
buttons[i][j] = new BattleShipButton(new Coordinate((char)i, j));
}
}
然后每个按钮都会有正确的坐标,您可以使用getCoordiantes()
。
答案 1 :(得分:0)
如果你想知道他们的位置,他们的指数应该足够了,只需在矩阵中执行它们。
如果你想更具体一点,你可以创建自己的按钮然后制作一个返回的功能,那个位置
答案 2 :(得分:0)
如果这可以帮助你,但不比没有好 我使用表单应用程序继续看看
您可以像这样创建一个数组
Button[] Barray = new Button[32,32];
than you will have to fill this array
for (int i = 0; i <= a - 1; i++)
{
for (int j = 0; j <= b - 1; j++)
{
Barray (i, j) = new Button(); // here you create a dynamic button
Barray (i, j).Location = new System.Drawing.Point(x, y); // here you locate the button in to your box or in a similar container
Barray (i, j).Size = new System.Drawing.Point(23, 23); // in this line you resize your button
Barray (i, j).Name = i + j; // in this lie you rename your button so that you will be able to reach your button and know what is its location
Barray (i, j).Click += Button_Click; // in this line you will add the button_click event to your dynamic buttons
Form1.box.Controls.Add(dizi(i, j)); // and this line adds your button to your container
x += 23; // in this line i am increasing the x location so i the buttons will not be placed at the same x location
}
x = 0; // this line i ll make x zero that means i m finis previous line and i ll start to place buttons on another line
y += 23; // this line i m increasing the y location to move the next line
}
在这些代码之后,我需要创建一个事件来捕捉按钮点击事件:)
private void button_Click(object sender, System.Windows.Forms.MouseEventArgs e)
{
//here you can use e eventargs reach your buttons name so you can do anything you want :)
}
希望这可以帮助你
答案 3 :(得分:0)
创建一个扩展AbstractAction的新类。给它坐标属性并创建新实例,并在创建按钮时传入JButton的构造函数。
这样做你将覆盖actionPerformed Action方法,允许你按下click事件来使用那些完美包装在同一个类中的坐标。