我认为,在所有标准布局中,GridBagLayout 应该最适合您的需要。
您可以尝试类似以下示例,其中我使用 addToLayout 将复杂的 GridBagConstraints 构造函数简化为我真正需要的。
但是,如果您可以使用 IDE,这确实可以使事情变得更容易(例如 NetBeans 中的 Matisse)。
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GridBagLayoutTest extends JPanel {
public GridBagLayoutTest() {
setLayout(new GridBagLayout());
addToLayout(new JLabel( "Label 0" ), 0, 0, 0d, 1);
addToLayout(new JTextField( "Field 0" ), 0, 1, 1d, 4);
addToLayout(new JLabel( "*" ), 0, 5, 0d, 1);
addToLayout(new JPanel() , 1, 0, 0d, 1);
addToLayout(new JLabel( "Label 1" ), 2, 0, 0d, 1);
addToLayout(new JTextField( "Field 1" ), 2, 1, 1d, 4);
addToLayout(new JLabel( "*" ), 2, 5, 0d, 1);
addToLayout(new JLabel( "Label 2" ), 3, 0, 0d, 1);
addToLayout(new JTextField( "Field 2" ), 3, 1, 1d, 1);
addToLayout(new JLabel( "*" ), 3, 2, 0d, 1);
addToLayout(new JLabel( "Label 3" ), 3, 3, 0d, 1);
addToLayout(new JTextField( "Field 3" ), 3, 4, 1d, 1);
addToLayout(new JLabel( "*" ), 3, 5, 0d, 1);
}
private void addToLayout(java.awt.Component comp, int y, int x, double weightx, int gridwidth) {
add(comp, new GridBagConstraints(x, y, gridwidth, 1, weightx, 0d,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new java.awt.Insets(2, 4, 2, 4), 0, 0 ) );
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GridBagLayoutTest());
frame.setSize(800, 600);
frame.setVisible(true);
}
}