: , pack, . pack , , () , . , , setPreferredSize, , .
- . GridLayout , , .
GridBagLayout, .

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Example extends JFrame {
String firstRow[] = {"~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "fill", "BackSpace"};
String secondRow[] = {"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"};
String thirdRow[] = {"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "\"", "fill", "fill", "Enter"};
String fourthRow[] = {"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", "blank", "^"};
String fifthRow[] = {"blank", "blank", "fill", "fill", "fill", "fill", "fill", "fill", "fill", "fill", "", "<", "v", ">"};
JButton first[];
JButton second[];
JButton third[];
JButton fourth[];
JButton fifth[];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Example().setVisible(true);
}
});
}
public Example() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initWidgets();
}
private void initWidgets() {
setLayout(new BorderLayout());
JPanel jpNorth = new JPanel();
JPanel jpCenter = new JPanel();
JPanel jpKeyboard = new JPanel(new GridBagLayout());
JPanel jpNote = new JPanel();
add(jpNorth, BorderLayout.NORTH);
add(jpNote);
add(jpCenter, BorderLayout.CENTER);
add(jpKeyboard, BorderLayout.SOUTH);
first = new JButton[firstRow.length];
second = new JButton[secondRow.length];
third = new JButton[thirdRow.length];
fourth = new JButton[fourthRow.length];
fifth = new JButton[fifthRow.length];
addKeys(jpKeyboard, 0, firstRow, first);
addKeys(jpKeyboard, 1, secondRow, second);
addKeys(jpKeyboard, 2, thirdRow, third);
addKeys(jpKeyboard, 3, fourthRow, fourth);
addKeys(jpKeyboard, 4, fifthRow, fifth);
pack();
}
protected void addKeys(JPanel parent, int row, String[] keys, JButton[] buttons) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = row;
gbc.gridx = 0;
gbc.fill = GridBagConstraints.BOTH;
int gap = 0;
for (int index = 0; index < keys.length; index++) {
String key = keys[index];
if ("blank".equalsIgnoreCase(key)) {
gbc.gridx++;
} else if ("fill".equalsIgnoreCase(key)) {
gbc.gridwidth++;
gap++;
} else {
System.out.println("Add " + key);
JButton btn = new JButton(key);
buttons[index] = btn;
parent.add(btn, gbc);
gbc.gridx += gap + 1;
gbc.gridwidth = 1;
gap = 0;
}
}
}
}
, , @peeskillet , , ... upvote , ;)