Java 如何在数组中创建单个按钮名称?

Java 如何在数组中创建单个按钮名称?,java,arrays,swing,jbutton,Java,Arrays,Swing,Jbutton,我想做一个战舰游戏,我控制着棋盘。我如何制作一个数组,允许每个按钮返回一个位置。用来存放飞船和撞击物。我想创建每个单独的按钮,但我不确定如何执行此操作。您可以扩展button类: public class BattleShipButton extends JButton { private Coordinate coords; public BattleShipButton(Coordinates coords) { this.coords = coords;

我想做一个战舰游戏,我控制着棋盘。我如何制作一个数组,允许每个按钮返回一个位置。用来存放飞船和撞击物。我想创建每个单独的按钮,但我不确定如何执行此操作。

您可以扩展button类:

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));
    }
}
battleshipputton[][]按钮=新的battleshipputton[boardWidth][boardHeight];
对于(int i=(int)'a';i

然后,每个按钮都会有正确的坐标,您可以使用
getCoordiantes()

在矩阵中进行操作,如果您想知道它们的位置,它们的索引就足够了


如果你想说得更具体一些,你可以创建自己的按钮,然后创建一个返回的功能,如果这个位置可以帮助你,那就不要了,但总比什么都没有好 我用过申请表去看看吧

您可以创建这样的数组

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
}

希望这能帮助您创建一个扩展AbstractAction的新类。为它指定坐标属性,创建新实例,并在创建按钮时传递给JButton的构造函数


在此过程中,您将覆盖actionPerformed操作方法,以允许您单击按钮事件来利用这些坐标,这些坐标都很好地打包在同一个类中。

JButton可能有一个属性,用于将位置保持在屏幕上。@Alan,正确,您可以使用
getLocation()
getLocationOnScreen()
但这只会提供像素坐标。这会给你逻辑上的战舰坐标。你在哪里看到问题中的C?
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 :)
}