2013-03-18 47 views
0

我试图通过单击该块上的第一个块,然后单击广场以将其移动,从网格中的一个方块移动到另一个块。使用ActionListener交换网格中的两个图标

如何保存第一个图标的位置,然后将其与第二个图标进行交换?

目前我在看这个代码,只是将一块一点平方米左右:

public void actionPerformed(ActionEvent e) 
{ 
for (x=0; x<8; x++) 
     for(y=0; y<8; y++) { 
     if(e.getSource() == board[x][y]) 
     ((ChessSquare)e.getSource()).swap(board[x][y-1]); 
    } 
} 

回答

1
  • 存储表示这是否是一个“拖”或“降” 标志。
  • 如果“拖动”存储原始坐标并将标志更改为“放下”。
  • 如果'drop'读取源的坐标,请按照原样使用它们并将该标志设置为'drag'。

  1. 我的意思是像声明boolean drag,并根据需要将其设置true/false

..最好的地方存储坐标吗?

我会用2个int属性,但如果你想滥用一个Dimension对象,只是一个可以同时存储X & y坐标ORDS。

..不,废话。使用mKorbel所示的客户端属性似乎更加“整洁”。

+0

将在其中存储的坐标最好的地方? – user2079483 2013-03-18 17:58:10

+0

看到编辑... – 2013-03-18 18:00:21

+1

可能[putClientProperty](http://stackoverflow.com/a/10385302/714968)是最简单的方法,肯定....,也许不是 – mKorbel 2013-03-18 18:21:25

0
  • 我们需要一个布尔标志,该标志将跟踪“点击”
  • 如果标志=假它的第一次点击,否则它的第二次点击(这是 ,我们会进行交换)。

    public void actionPerformed(ActionEvent e) 
    { 
        int xPos1,xPos2,yPos1,yPos2; 
        if(!flag) 
        { 
         for (x=0; x<8; x++) 
         { 
          for(y=0; y<8; y++) 
          { 
          if(e.getSource() == board[x][y]) 
          { 
           xPos1 = x; // Source icon cordinates. 
           yPos2 = y; 
           break; 
          } 
          } 
         } 
         flag = true; 
        } 
        else 
        { 
         for (x=0; x<8; x++) 
         { 
         for(y=0; y<8; y++) 
         { 
          if(e.getSource() == board[x][y]) 
          { 
          xPos2 = x; // Target icon cordinates. 
          yPos2 = y; 
          break; 
          } 
         } 
         } 
    
         // Swapping code add your version of this swapping code here. 
         // Swap source with target. 
         Icon temp = board[xPos1][yPos1] 
         board[xPos1][yPos1] = board[xPos2][yPos2]; 
         board[xPos2][yPos2] = temp;   
         // ----------------- End Swap---------------- 
    
         flag = false; // ready for next swap operation. 
        } 
    

    }

+0

应该是非常复杂的,在我的评论中看到另一个问题的代码在这里, – mKorbel 2013-03-18 18:22:18