Java tutorial
//package com.java2s; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.plaf.metal.MetalLookAndFeel; public class Main { static final String LAF_METAL = MetalLookAndFeel.class.getName(); public static JPanel createKV(final Component key, final Component value) { return createKV(key, value, true); } public static JPanel createKV(final Component key, final Component value, final boolean fill) { return createKV(key, value, 60, fill); } public static JPanel createKV(final Component key, final Component value, final int keyWidth) { return createKV(key, value, keyWidth, true); } public static JPanel createKV(final Component key, final Component value, final int keyWidth, final boolean fill) { initComponentHeight(key, value); if (keyWidth > 0) { key.setPreferredSize(new Dimension(keyWidth, key.getPreferredSize().height)); } final JPanel jp = new JPanel(new GridBagLayout()); final GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(0, 0, 0, 4); jp.add(key, gbc); gbc.gridx = 1; gbc.insets = new Insets(0, 0, 0, 0); gbc.weightx = 1.0; if (fill) { gbc.fill = GridBagConstraints.HORIZONTAL; } jp.add(value, gbc); return jp; } public static void initComponentHeight(final Component... components) { if (components == null) { return; } for (final Component component : components) { if ((component instanceof JComboBox) || (component instanceof JButton)) { component.setPreferredSize(new Dimension(component.getPreferredSize().width, 22)); } else if (component instanceof JTextField) { final String lf = UIManager.getLookAndFeel().getClass().getName(); int i = 22; if (lf.equals(LAF_METAL)) { i = 23; } component.setPreferredSize(new Dimension(component.getPreferredSize().width, i)); } } } }