在 GridBagLayout 中使用 Java 分配额外的水平和垂直空间


想要分配额外的水平和垂直空间,请使用字段 weightx 和 weighty。以下是分配额外水平和垂直空间的一个示例 −

示例

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;
      gbc.weightx = 2;
      gbc.weighty = 2;
      layout.setConstraints(label, gbc);
      panel.add(label);
      gbc.gridx = 1;
      gbc.gridy = 1;
      gbc.weightx = 2;
      gbc.weighty = 2;
      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 日

538 次浏览

开启你的职业生涯

完成课程,获得认证

开始
广告