如何在同一行内使用 GridBagConstraints 在 Java 中布局两个组件
要将两个组件对齐到同一行,需要正确设置 GridBagConstraints 的约束。假设我们的 panel1 中有两个组件。使用 Insets 以及类似设置约束条件 -
panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
以下是如何将两个组件设置到同一行中的示例 -
示例
package my; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setSize(550, 300); JPanel panel1 = new JPanel(new GridBagLayout()); JCheckBox checkBox1 = new JCheckBox("Undergraduate"); JCheckBox checkBox2 = new JCheckBox("Graduate"); panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0, 0, 0), 0, 0)); panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0, 0, 0), 0, 0)); frame.add(panel1); frame.setVisible(true); } }
输出
广告