• 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

概要

GridBagLayoutを使用してJButtonをキーボード状に配置します。

サンプルコード

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;
}
View in GitHub: Java, Kotlin

解説

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

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

参考リンク

コメント