如何获取 Java 中 JButton 的 gridlayout 单元格位置?

How to get the gridlayout cell position of a JButton in Java?

我正在 java 中使用几个按钮制作一个猜谜游戏。该程序使用 java gridlayout 布局,当单击按钮时,我希望它将其 GridLayout 位置(不是 x 和 y)添加到数组中。

这是一段需要单元格位置查找器的代码。

    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);
    }
}

这不是最简单的事情...可能将 JButton 保存在二维数组中更有用,或者更好地保存 JButton 的地图来定位。

如果您真的必须从按钮中辨别网格单元,请调用

JPanel.getComponents()(或任何父容器),然后在其中找到您的 Button。然后算一下。

假设您在索引 6 处找到它。

然后因为你的网格是 x x y 除以 x 得到行,mod x 得到列。

所以说网格 ix 4x4

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

6 % 4 是 2,所以你在索引为 2 的列(第三列)