weightx 和weighty这两个属性表示当Container的大小被改变时,
组件本身大小的收缩和扩张能力
比如你设置了一个JLabel的weightx 和weighty为0
那么,无论你如何放大主窗口,这个Jlabel始终不改变大小和他的相对位置(既没有空隙)
自己试一试吧!
import java.awt.*;
import javax.swing.*;public class test13
{
   public static void main(String[] args)
   {
  FontDialogFrame frame = new FontDialogFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.show();
   }
}class FontDialogFrame extends JFrame
{
   public FontDialogFrame()
   {
  setTitle("FontDialog");
  setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);   Container contentPane = getContentPane();
  GridBagLayout layout = new GridBagLayout();
  contentPane.setLayout(layout);   // construct components   JLabel faceLabel = new JLabel("Face: ");   face = new JComboBox(new String[]
 {
"Serif", "SansSerif", "Monospaced",
"Dialog", "DialogInput"
 });
  JLabel sizeLabel = new JLabel("Size: ");   size = new JComboBox(new String[]
 {
"8", "10", "12", "15", "18", "24", "36", "48"
 });
  bold = new JCheckBox("Bold");   italic = new JCheckBox("Italic");   sample = new JTextArea();
  sample.setText(
 "The quick brown fox jumps over the lazy dog");
  sample.setEditable(false);
  sample.setLineWrap(true);
  sample.setBorder(BorderFactory.createEtchedBorder());   // add components to grid   GridBagConstraints constraints = new GridBagConstraints();   constraints.fill = GridBagConstraints.NONE;
  constraints.anchor = GridBagConstraints.EAST;
  constraints.weightx = 0;
  constraints.weighty = 0;   add(faceLabel, constraints, 0, 0, 1, 1);
  add(sizeLabel, constraints, 0, 1, 1, 1);   constraints.fill = GridBagConstraints.HORIZONTAL;
  constraints.weightx = 100;   add(face, constraints, 1, 0, 1, 1);
  add(size, constraints, 1, 1, 1, 1);   constraints.weighty = 100;
  constraints.fill = GridBagConstraints.NONE;
  constraints.anchor = GridBagConstraints.CENTER;   add(bold, constraints, 0, 2, 2, 1);
  add(italic, constraints, 0, 3, 2, 1);   constraints.fill = GridBagConstraints.BOTH;
  add(sample, constraints, 2, 0, 1, 4);
   }
   
   public void add(Component c, GridBagConstraints constraints,
  int x, int y, int w, int h)
   {
  constraints.gridx = x;
  constraints.gridy = y;
  constraints.gridwidth = w;
  constraints.gridheight = h;
  getContentPane().add(c, constraints);
   }   public static final int DEFAULT_WIDTH = 300;
   public static final int DEFAULT_HEIGHT = 200;   private JComboBox face;
   private JComboBox size;
   private JCheckBox bold;
   private JCheckBox italic;
   private JTextArea sample;
}