有效決定 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中文網其他相關文章!