用 Java 在 GridBagLayout 中設定元件的位置


要設定元件的位置,請使用 GridBagConstraints。在此,我們有兩個元件 -

GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel("Email-Id − ");
JTextArea text = new JTextArea();
text.setText("Add id here...");

使用 gridx 和 gridy 設定位置 -

gbc.gridx = 0;
gbc.gridy = 0;
layout.setConstraints(label, gbc);
panel.add(label);

以下是一個在 GridBagLayout 中設定元件位置的示例 -

示例

package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      GridBagLayout layout = new GridBagLayout();
      panel.setLayout(layout);
      GridBagConstraints gbc = new GridBagConstraints();
      JLabel label = new JLabel("Email-Id − ");
      JTextArea text = new JTextArea();
      text.setText("Add id here...");
      gbc.gridx = 0;
      gbc.gridy = 0;
      layout.setConstraints(label, gbc);
      panel.add(label);
      gbc.gridx = 1;
      gbc.gridy = 1;
      layout.setConstraints(text, gbc);
      panel.add(text);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

輸出

更新時間: 2019 年 7 月 30 日

425 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.