2014-11-16 68 views
0

首先發布在這裏,但很長時間的讀者,一直在尋找,但無法找到一個完全有助於我的問題的帖子。獲取JLabels二維數組的位置

我想用mouselisteners創建JLabels的2D網格,並檢索點擊JLabel的X/Y位置,但無法找到一種方法來做到這一點。我嘗試了幾個方法,我發現在這個網站上,但沒有任何工作。

目前我有以下....

 pcenter.setLayout(new GridLayout(game.getXSize(), game.getYSize())); 
    pcenter.setBorder(new EmptyBorder(8,8,8,8)); 
    pcenter.setPreferredSize(new Dimension((game.getXSize() * 30), (game.getYSize() * 30))); 
    gamegrid = new JLabel[game.getXSize()][game.getYSize()]; 
    for (int i = 0; i < game.getXSize(); i++) { 
     for (int j = 0; j < game.getYSize(); j++) { 
      gamegrid[i][j] = new JLabel(); 
      gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); 
      gamegrid[i][j].addMouseListener(new MouseAdapter() { 
       public void mousePressed(MouseEvent e) { 
       } 
      }); 
      pcenter.add(gamegrid[i][j]); 
     } 
    } 

「遊戲」是容納用於,我想在的JLabel的相同座標通過點擊對象的2D陣列的對象。點擊gamegrid [2] [5]的E.G將聯繫game.plots [2] [5]。

每當我嘗試做一個變量來存儲2和5它想使方法FINAL,如果我把該方法放在MouseAdapter()它想要使'我'或'j'FINAL。

請幫助:)提前致謝。

回答

0

只是想通了!我會在這裏發佈,只是包裝別人想知道的。

我創建類中的其他3個變量:

private static Object source; 
private static int currentX, currentY; 

那麼當前的MouseListener,它現在是,我添加了以下內容:

 for (int i = 0; i < game.getXSize(); i++) { 
     for (int j = 0; j < game.getYSize(); j++) { 

      gamegrid[i][j] = new JLabel(); 
      gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); 
      gamegrid[i][j].addMouseListener(new MouseAdapter() { 
       public void mousePressed(MouseEvent e) { 

        source = e.getSource(); //added this to get the mouseevent object. 
        XYsource(); // this is a method to turn the object source 
            into X and Y coords. 

       } 
      }); 
      pcenter.add(gamegrid[i][j]); 
     } 
    } 

最後下面的方法來轉動將對象源代入X和Y座標

public static void XYsource() { 

    int maxX = game.getXSize(); 
    int maxY = game.getYSize(); 

    for(int i = 0; i < maxX; i++) { 
     for(int j = 0; j < maxY; j++){ 
      if (gamegrid[i][j] == source) { 
       currentX = i; 
       currentY = j; 
      } 
     } 
    } 

    updateXY(); // this is just a method to set text on the screen showing 
        the X and Y coordinates to test the MouseListener 
}