Swing/KeyboardLayout のバックアップ(No.11)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/KeyboardLayout へ行く。
- 1 (2019-04-08 (月) 15:20:12)
- 2 (2019-04-12 (金) 16:39:38)
- 3 (2019-05-28 (火) 16:23:05)
- 4 (2019-10-16 (水) 16:34:30)
- 5 (2021-05-20 (木) 07:51:42)
- 6 (2024-02-02 (金) 11:49:01)
- 7 (2024-10-07 (月) 07:01:23)
- 8 (2025-01-03 (金) 08:57:02)
- 9 (2025-01-03 (金) 09:01:23)
- 10 (2025-01-03 (金) 09:02:38)
- 11 (2025-01-03 (金) 09:03:21)
- 12 (2025-01-03 (金) 09:04:02)
- 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
をキーボード状に配置します。
Screenshot

Advertisement
Source Code Examples
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, KotlinExplanation
上記のサンプルでは、GridBagLayout
を使用して高さ0
で列幅のみの非表示セルを配置したガイド行を作成し、1
文字のデフォルトキーはその2
列分占有するJButton
を配置してキーボード風のレイアウトを表現しています。
- スペースキーは
14
列分占有するJButton
を配置 - Shift、Enterキーは
4
列分占有するJButton
を配置 - Tab、Ctrl、Altなどは
3
列分占有するJButton
を配置- Ctrlなどは
JToggleButton
にしたほうが良さそう
- Ctrlなどは
- 空文字列は
1
列分占有する不可視の固定幅コンポーネントを配置 - このサンプルの各
JButton
にはイベントを設定していないのでクリックしても無反応
参考リンク
- java - Laying out a keyboard in Swing - Stack Overflow
- GridBagLayoutを使ってレンガ状に配置
- JButton内に複数のJLabelをBorderLayoutで配置する