首页 >Java >java教程 >如何有效确定 GridLayout 中元素的 X 和 Y 坐标?

如何有效确定 GridLayout 中元素的 X 和 Y 坐标?

Linda Hamilton
Linda Hamilton原创
2025-01-03 21:24:41349浏览

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

有效确定 GridLayout 中的元素坐标

识别 GridLayout 中特定元素的 x 和 y 坐标通常会带来挑战。虽然常见的方法涉及遍历按钮的二维数组来建立它们的关系,但存在一种更有效的方法。

这种替代方法利用包含组件的 getComponentXIndex() 和 getComponentYIndex() 方法。通过引用事件源,这些方法可以快速提供所需的坐标。

例如,考虑以下 Java 代码片段:

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

此代码有效地检索 x 和 y基于事件源的按钮索引。

在提供的 Java Swing 应用程序示例中, getGridButton() 方法在获取使用网格坐标有效地引用按钮。此外,动作侦听器演示了单击和找到的按钮的等效性。

增强的 GridButtonPanel 类例证了这种方法,其中每个按钮由其在网格内的坐标唯一标识。单击任何按钮后,代码都会验证预期按钮引用与实际按钮引用之间的一致性。

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

这种增强的方法简化了在 GridLayout 中获取元素坐标的过程,无需复杂的遍历并提高效率.

以上是如何有效确定 GridLayout 中元素的 X 和 Y 坐标?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn