---
category: swing
folder: KeyboardLayout
title: GridBagLayoutを使ってJButtonをキーボード状に配置する
tags: [GridBagLayout, JButton, LayoutManager]
author: aterai
pubdate: 2019-04-08T15:13:08+09:00
description: GridBagLayoutを使用してJButtonをキーボード状に配置します。
image: https://drive.google.com/uc?id=1U-lm1O1GYxe612eOeM5DwMWUdIUpD2JXnQ
hreflang:
    href: https://java-swing-tips.blogspot.com/2019/04/use-gridbaglayout-to-layout-jbutton.html
    lang: en
---
* 概要 [#summary]
`GridBagLayout`を使用して`JButton`をキーボード状に配置します。

#download(https://drive.google.com/uc?id=1U-lm1O1GYxe612eOeM5DwMWUdIUpD2JXnQ)

* サンプルコード [#sourcecode]
#code(link){{
private static final String[][] KEYS = {
  {"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "BS"},
  {"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\", ""},
  {"Ctrl", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter", ""},
  {"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "", "↑"},
  {"Fn", "Alt", "                             ", "Alt", "←", "↓", "→"}
};

private static Component makeKeyboardPanel() {
  JPanel keyboard = new JPanel(new GridBagLayout());

  GridBagConstraints c = new GridBagConstraints();
  c.fill = GridBagConstraints.BOTH;
  c.gridy = 50;
  for (int i = 0; i < KEYS[0].length * 2; i++) {
    c.gridx = i;
    keyboard.add(Box.createHorizontalStrut(KeyButton.SIZE));
  }

  for (int row = 0; row < KEYS.length; row++) {
    c.gridx = 0;
    c.gridy = row;
    for (int col = 0; col < KEYS[row].length; col++) {
      String key = KEYS[row][col];
      int len = key.length();
      c.gridwidth = len > 10 ? 14
                  : len > 4  ? 4
                  : len > 1  ? 3
                  : len == 1 ? 2 : 1;
      if (key.isEmpty()) {
        keyboard.add(Box.createHorizontalStrut(KeyButton.SIZE), c);
      } else {
        keyboard.add(new KeyButton(key, len <= 2), c);
      }
      c.gridx += c.gridwidth;
    }
  }
  EventQueue.invokeLater(() -> SwingUtilities.updateComponentTreeUI(keyboard));
  return keyboard;
}
}}

* 解説 [#explanation]
上記のサンプルでは、`GridBagLayout`を使用してダミーの列幅を持つガイド行を作成し、`1`文字のデフォルトキーはその`2`列分占有する`JButton`を配置してキーボード風のレイアウトを表現しています。

- 各`JButton`にはイベントを設定していないので、クリックしても無反応
- スペースキーは`14`列分占有する`JButton`を配置
- KBD{Shift}、KBD{Enter}キーは`4`列分占有する`JButton`を配置
- KBD{Tab}、KBD{Ctrl}、KBD{Alt}などは`3`列分占有する`JButton`を配置
-- KBD{Ctrl}などは`JToggleButton`にしたほうが良さそう
- 空文字列は`1`列分占有する不可視の固定幅コンポーネントを配置

* 参考リンク [#reference]
- [https://stackoverflow.com/questions/24622279/laying-out-a-keyboard-in-swing java - Laying out a keyboard in Swing - Stack Overflow]
- [[GridBagLayoutを使ってレンガ状に配置>Swing/BrickLayout]]

* コメント [#comment]
#comment
#comment