2016-12-04 65 views
-2

我正在使用幾個按鈕在java中進行猜測網格遊戲。該程序使用java gridlayout佈局,當單擊按鈕時,我希望它將GridLayout位置(不是x & y)添加到數組中。如何獲取Java中的JButton的gridlayout單元格位置?

這裏是需要單元格定位器的代碼條。

public void actionPerformed(ActionEvent e) 
    { 


     if(placementLimit < 5){ 

     //placementlimit is limit to buttons clicked 

     JButton clickedButton = (JButton)e.getSource(); 

     clickedButton.setBackground(Color.RED); 
     /* something like: int pos = clickedButton.getGridPos 
     * arrayplacedpositions.add(pos); 
     */ 
     placementLimit++; 
    } 

我沒有做一個JPanel所以 整個項目是在這裏:

 /* Guessing game GoldMiner By Alexander Smirnov 
* A Computer Game where you hide and place gold. 
*/ 
package standard; 

import java.awt.Color; 
import java.awt.Container; 
import java.awt.GridLayout; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyEvent; 
import java.util.ArrayList; 
import java.util.Arrays; 


import javax.swing.*; 

public class game extends JPanel 
{ 
    JButton buttons[] = new JButton[64]; 
    int placementLimit = 0; 
    ArrayList goldPos = new ArrayList(); 


    public game() 
    { 
     setLayout(new GridLayout(8,8)); 
     initializebuttons(); 
    } 


    public void initializebuttons() 
    { 
     for(int i = 0; i <= 63; i++) 
     { 
      buttons[i] = new JButton(); 
      buttons[i].setText(""); 
      buttons[i].addActionListener(new buttonListener()); 

      add(buttons[i]); 
     } 
    } 



    private class buttonListener implements ActionListener 
    { 

     public void actionPerformed(ActionEvent e) 
     { 


      if(placementLimit < 5){ 
      JButton clickedButton = (JButton)e.getSource(); 
      clickedButton.setIcon(new ImageIcon("/Users/Administrator/Desktop/gold2.jpg")); 
      clickedButton.setBackground(Color.RED); 
      JPanel.getComponents(); 
      placementLimit++; 
     } else { 


      JOptionPane.showMessageDialog(null, "You have placed the maximum amount of gold!"); 

      } 

      } 






    } 
    public static void main(String[] args) 
    { 
     JFrame window = new JFrame("GoldMiner"); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.getContentPane().add(new game()); 
     window.setBounds(300,200,300,300); 
     Container c = window.getContentPane(); 

     window.setVisible(true); 
    } 
} 
+0

如果這不是重複的,請編輯您的問題以包含顯示您修改方法的[mcve]。 – trashgod

回答

2

這不是最容易做的事情......有可能會握住你的JButton S IN更有用一個2D陣列,或者更好地保存一張JButton的位置圖。

如果你真的必須辨別從按鈕的柵格單元,稱之爲

JPanel.getComponents()(或任何父容器是),並找到你的按鈕在那裏。然後做數學。

說你在指數6

則由於網格爲x由x和y分拿到行,國防部通過X拿到列中找到它。

所以說網格IX的4x4

6/4是1,所以你是與索引1(第二行)

6%4爲2的行中,所以你與列索引2(第三列)

+0

你可以給一個代碼示例。 –

+0

此外,我的按鈕是使用for循環形成的,所以我無法手動調用每個按鈕。 –

+0

(1+)的好建議。另外,我不確定它是否是一個kludge,但是在創建時使用'putClientProperty(...)'方法可以將網格位置填充到JButton中。 –