I've been trying to reproduce this layout:
Here I am:
using:
import javax.swing.*;
import java.awt.*;
public class Keyb {
private JFrame f = new JFrame("Keyboard");
private JPanel keyboard = new JPanel();
private static final String[][] key = {
{"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace"},
{"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"},
{"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter"},
{"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "Shift", "\u2191"},
{" ", "\u2190", "\u2193", "\u2192"}
};
public Keyb() {
keyboard.setLayout(new GridBagLayout());
JPanel pRow;
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.weightx = 1d;
for (int row = 0; row < key.length; ++row) {
pRow = new JPanel(new GridBagLayout());
c.gridy = row;
for (int col = 0; col < key[row].length; ++col)
pRow.add(new JButton(key[row][col]));
keyboard.add(pRow, c);
}
f.add(keyboard);
}
public void launch() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
Keyb ui = new Keyb();
ui.launch();
}
}
How do I adjust the size of the buttons and align them perfectly, especially Tab
, Caps
, Shift
, Backspace
, Enter
and the spacebar, perhaps without using the set?Size methods?
Can it be done in a better way with other layout managers?
New at Java, so any other suggestions are welcome.
When all else fails, write it your self...
This uses a custom layout manager which defines a "basic" grid but allows components in a given row to expand into portions of the following column(s)...
The default cell size is defined by the largest width/height of the available components that doesn't expand beyond it's own column, makes things a little more even.
Currently the output is anchored to the top/left corner, but I'm sure you can figure out how to calculate the x/y offset needed to get it centered ;)
Another approach. The only restriction is the use of a mono-spaced font to maintain the alignment.