GUI-国际象棋游戏将碎片拖放到棋盘“ 2D阵列”

时间:2018-11-24 17:56:26

标签: java swing user-interface

你好,我正在尝试下棋游戏,到目前为止,我已经创建了棋子,并且可以用鼠标移动它们。

现在,我正在尝试使用包含棋子的2D阵列制作棋盘,因此当我在棋盘上拖动棋子时,它会将棋子添加到数组中,例如在图像上

我将作品拖到(2,3)board[2][3] = pawn

Example

但是我不确定如何实现它,我想过使用像将其拖动到中间时那样的坐标,说我的帧尺寸为800x800,板尺寸为8,所以当我将其拖动到坐标上时(400,400)board[4][4] = pawn,但是我必须为每个单元格做一次,如果有条件,我将得到64,是否有某种技巧可以解决?还是我的方法错误?

If( piece's position is between ... and ... ){
then put into board[0][1]}

If ( piece's position is between ... ) {
then put then put into board[1][1]} 

1 个答案:

答案 0 :(得分:0)

您可以在开发板上的JLabel上使用mouseListener!首先,使用8 * 8(chess是8 * 8,对吗?)JLabel来构建板,并将它们存储在某个数组中。

JLabel[][] boardFields = new JLabel[8][8];

您可以将它们打包在具有GridBagLayout的JPanel中。通过使用GridBagContraints类的'v gridxgridy变量,可以很容易地按所需的样式布置它们。

现在您要做的是在某个地方创建一个静态变量,将其称为selectedPiece。让我们将鼠标侦听器添加到我们所有的字段标签中:

for(int i=0;i<8;i++){
   for(int j=0;j<8;j++){

      boardFields[i][j] = new JLabel();
      //set its background white or black here

      //each field will listen to a mouse press (means we selected this piece)
      //and a mouse release (meaning we placed the selected piece here)
      boardFields[i][j].addMouseListener(new MouseAdapter(){

           public void mousePressed(MouseEvent e){
                selectedPiece = //set piece on this field somehow
                //update the background to plain black or white
                //make the icon of the piece follow the cursor
           }

           public void mousePressed(MouseEvent e){
                //update the background to contain the selectedPiece
                //make the icon of the piece stop followin the cursor
                 selectedPiece = null //de-select the piece since we just placed it
           }
      )};
   }
}

显然,这只是一个草图,但是它应该可以给您带来灵感!