请问,我要让三个JLabel水平放在一个JPanel里,
并且按照JPanel总长度的 40%,50%,10% 分布,要不留空隙.
请教各位大侠了!

解决方案 »

  1.   

    用GridBagLayout做吧,JPanel.setLayout(new GridBagLayout());
    GridBagConstraints g = new GridBagConstraints();
    g.gridx = 0;
    g.gridy = 0;
    g.gridwidth = 1;
    g.gridheight = 1;
    g.weightx = 0.4;//40%
    g.weighty = 1.0;
    JPanel.add(JLabel1,g);
    g.gridy = 1;
    g.weightx = 0.5;//50%
    JPanel.add(JLabel2,g);
    g.gridy = 2;
    g.weightx = 0.1;//10%
    JPanel.add(JLabel3,g);
      

  2.   

    感谢Kacisusu!我修改了下代码,如果要obj4重叠在 obj1,obj2,obj3上面,并且能透明背景色,能自动缩放,如何做到?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;public class test extends JFrame {
    private JFrame frame = null;
    private JPanel pane = null;
    private int gridx, gridy, gridwidth, gridheight, anchor, fill, ipadx,
    ipady;
    private double weightx, weighty;
    private Insets insert; public test() {
    frame = new JFrame("Test");
    pane = new JPanel();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = null;
    pane.setLayout(gbl);
    //
    JLabel obj1 = new JLabel("1");
    obj1.setBorder(BorderFactory.createLineBorder(Color.black));
    JLabel obj2 = new JLabel("2");
    obj2.setBorder(BorderFactory.createMatteBorder(
                    1, 5, 1, 1, Color.red));
    JLabel obj3 = new JLabel("3");
    obj3.setBorder(BorderFactory.createLineBorder(Color.black));
    JLabel obj4 = new JLabel("down"); gridx = 0;
    gridy = 0;
    gridwidth = 1;
    gridheight = 1;
    insert = new Insets(0, 0, 0, 0); //the gap between components
    //


    //
    weightx = 0.5;
    weighty = 0.0;
    anchor = gbc.NORTH;
    fill = gbc.HORIZONTAL;

    gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight,
    weightx, weighty, anchor, fill, insert, ipadx, ipady);
    gbl.setConstraints(obj1, gbc);
    pane.add(obj1); gridx = 1;
    weightx = 0.3;
    anchor = gbc.CENTER;
    fill = gbc.BOTH;
    gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight,
    weightx, weighty, anchor, fill, insert, ipadx, ipady);
    gbl.setConstraints(obj2, gbc);
    pane.add(obj2); gridx = 2;
    weightx = 0.2;
    anchor = gbc.CENTER;
    fill = gbc.BOTH;
    gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight,
    weightx, weighty, anchor, fill, insert, ipadx, ipady);
    gbl.setConstraints(obj3, gbc);
    pane.add(obj3);

    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.getContentPane().add(pane);
    frame.setSize(300, 200);
    frame.setVisible(true);
    } public static void main(String args[]) {
    test t = new test();
    }}