GirdBagLayout布局中如何设置label范围
也就是让label宽度一定,
无论label中字符串多长,label都一样宽。
不会影响到画面的布局。

解决方案 »

  1.   

    label.setPreferredSize(new Dimension(width, height));
      

  2.   

    好像好使
    package test;import java.applet.Applet;
    import java.awt.*;import javax.swing.JFrame;
    import javax.swing.JLabel;public class GridBagExCopy extends Applet {    private static final long serialVersionUID = 1L;    protected void makebutton(String name, GridBagLayout gridbag,
                GridBagConstraints c) {
            Button button = new Button(name);
            gridbag.setConstraints(button, c);
            this.add(button);
        }    public void init() {
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints constraints = new GridBagConstraints();        setFont(new Font("SansSerif", Font.PLAIN, 14));
            this.setLayout(gridbag);        constraints.fill = GridBagConstraints.BOTH;
            constraints.weightx = 1.0;
            makebutton("Button2", gridbag, constraints);
            makebutton("Button3", gridbag, constraints);
            JLabel button = new JLabel("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            button.setPreferredSize(new Dimension(10, -1));
            button.setMinimumSize(new Dimension(0, -1));
            gridbag.setConstraints(button, constraints);
            this.add(button);        constraints.gridwidth = GridBagConstraints.REMAINDER; // end row
            makebutton("Button4", gridbag, constraints);        setSize(300, 200);
        }    public static void main(String args[]) {
            JFrame f = new JFrame("GridBag Layout Example");
            GridBagExCopy ex1 = new GridBagExCopy();        ex1.init();        f.add("Center", ex1);
            f.pack();
            f.setSize(f.getPreferredSize());
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }