如何在同一行內使用 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);
   }
}

輸出


更新於: 2019 年 7 月 30 日

254 次瀏覽

開啟您的 事業

透過完成課程獲取認證

開始
廣告
© . All rights reserved.