Home >Java >javaTutorial >How Can I Efficiently Determine the X and Y Coordinates of an Element in a GridLayout?

How Can I Efficiently Determine the X and Y Coordinates of an Element in a GridLayout?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 21:24:41269browse

How Can I Efficiently Determine the X and Y Coordinates of an Element in a GridLayout?

Efficiently Determining Element Coordinates Within a GridLayout

Identifying the x and y coordinates of a specific element within a GridLayout can often pose a challenge. While a common approach involves traversing a bidimensional array of buttons to establish their relationship, a more efficient method exists.

This alternative approach leverages the getComponentXIndex() and getComponentYIndex() methods of the containing component. By referencing the source of an event, these methods can swiftly provide the desired coordinates.

For instance, consider the following Java code snippet:

JButton button = (JButton) ev.getSource();
int x = this.getContentPane().getComponentXIndex(button);
int y = this.getContentPane().getComponentYIndex(button);

This code effectively retrieves the x and y indices of the button based on its event source.

In the provided Java Swing Application example, the getGridButton() method plays a pivotal role in obtaining the button reference efficiently using the grid coordinates. Furthermore, the action listener demonstrates the equivalence of the clicked and found buttons.

The enhanced GridButtonPanel class exemplifies this approach, where each button is uniquely identified by its coordinates within the grid. Upon clicking any button, the code verifies the consistency between the expected and actual button references.

package gui;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see http://stackoverflow.com/questions/7702697
 */
public class GridButtonPanel {

    private static final int N = 5;
    private final List<JButton> list = new ArrayList<>();

    private JButton getGridButton(int r, int c) {
        int index = r * N + c;
        return list.get(index);
    }

    private JButton createGridButton(final int row, final int col) {
        final JButton b = new JButton("r" + row + ",c" + col);
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton gb = GridButtonPanel.this.getGridButton(row, col);
                System.out.println("r" + row + ",c" + col
                    + " " + (b == gb)
                    + " " + (b.equals(gb)));
            }
        });
        return b;
    }

    private JPanel createGridPanel() {
        JPanel p = new JPanel(new GridLayout(N, N));
        for (int i = 0; i < N * N; i++) {
            int row = i / N;
            int col = i % N;
            JButton gb = createGridButton(row, col);
            list.add(gb);
            p.add(gb);
        }
        return p;
    }

    private void display() {
        JFrame f = new JFrame("GridButton");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(createGridPanel());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GridButtonPanel().display();
            }
        });
    }
}

This enhanced approach simplifies the process of obtaining element coordinates within a GridLayout, eliminating the need for complex traversals and improving efficiency.

The above is the detailed content of How Can I Efficiently Determine the X and Y Coordinates of an Element in a GridLayout?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn