Swing/PositionInGridLayout のバックアップソース(No.1)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- バックアップ を表示
- Swing/PositionInGridLayout へ行く。
- 1 (2019-06-17 (月) 16:18:31)
- 2 (2021-02-25 (木) 10:45:41)
--- category: swing folder: PositionInGridLayout title: GridLayout内でのセル位置を取得する tags: [GridLayout, JPanel, LayoutManager] author: aterai pubdate: 2019-06-17T16:13:12+09:00 description: GridLayoutを設定したJPane内lに配置したJButtonをクリックしたときそのセル位置を取得します。 image: https://drive.google.com/uc?id=1rdkSt62Po3ua2bJiL0XWH4IGa8DGjkom --- * 概要 [#summary] GridLayoutを設定したJPane内lに配置したJButtonをクリックしたときそのセル位置を取得します。 #download(https://drive.google.com/uc?id=1rdkSt62Po3ua2bJiL0XWH4IGa8DGjkom) * サンプルコード [#sourcecode] #code(link){{ GridLayout gl = new GridLayout(5, 7, 5, 5); JPanel p = new JPanel(gl); p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JTextArea log = new JTextArea(3, 0); ActionListener al = e -> { JComponent c = (JComponent) e.getSource(); int idx = p.getComponentZOrder(c); int row = idx / gl.getColumns(); int col = idx % gl.getColumns(); log.append(String.format("Row: %d, Column: %d%n", row + 1, col + 1)); }; for (int i = 0; i < gl.getRows() * gl.getColumns(); i++) { JButton b = new JButton(); b.addActionListener(al); p.add(b); } }} * 解説 [#explanation] - `Container#getComponentZOrder(Component)`で、コンテナ(`JPanel`)内のコンポーネント(`JButton`)の`Z`軸順インデックスを取得 - `GridLayout#getColumns()`でレイアウト(`GridLayout`)内の列数を取得 -- `Z`軸順インデックスを列数で割りコンポーネントの存在する行番号を取得 -- `Z`軸順インデックスを列数で剰余しコンポーネントの存在する列番号を取得 - 最初のセル(左上)は`(0, 0)`なので行列にそれぞれ`1`足してコンポーネントの存在するセル位置を`JTextArea`に表示 * 参考リンク [#reference] * コメント [#comment] #comment #comment