如何在 GridBagLayout 中設定 columnWeights 和 rowWeights?


建立一個面板並設定佈局 -

JPanel panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);

現在,設定約束以及 columnWeights 和 rowWeights -

GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel("Rank: ");
JTextArea text = new JTextArea();
text.setText("Add rank here...");
layout.columnWeights = new double[]{0.0f, 0.0f, 2.0f};
layout.rowWeights = new double[]{0.0f, 1.0f};

現在,為標籤設定約束並將其新增到面板 -

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

以下是如何在 GridBagLayout 中設定 columnWeights 和 rowWeights 的示例 -

示例

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("Rank: ");
      JTextArea text = new JTextArea();
      text.setText("Add rank here...");
      layout.columnWeights = new double[]{0.0f, 0.0f, 2.0f};
      layout.rowWeights = new double[]{0.0f, 1.0f};
      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 日

154 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.