Alternative to absolute layout?

前端 未结 3 771
礼貌的吻别
礼貌的吻别 2021-01-15 14:15

Is there a layout manager that gives the same degree of control as Absolute Positioning? But also makes auto resizing possible? Something where you could place elements usi

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 14:26

    Another option is to use a SpringLayout(personally, I like a GridBagLayout).

    enter image description here

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import static javax.swing.SpringLayout.*;
    
    public class SpringScaleTest {
      public JComponent makeUI() {
        SpringLayout layout = new SpringLayout();
        JPanel p = new JPanel(layout);
        p.setBorder(BorderFactory.createLineBorder(Color.GREEN, 10));
    
        JLabel  l1 = new JLabel("label: width=90%", SwingConstants.CENTER);
        l1.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
        JButton l2 = new JButton("button: width=50%");
    
        Spring panelw = layout.getConstraint(WIDTH, p);
    
        SpringLayout.Constraints c1 = layout.getConstraints(l1);
        c1.setX(Spring.constant(0));
        c1.setY(Spring.constant(20));
        c1.setWidth(Spring.scale(panelw, 0.9f));
        p.add(l1);
    
        SpringLayout.Constraints c2 = layout.getConstraints(l2);
        c2.setWidth(Spring.scale(panelw, 0.5f));
        layout.putConstraint(SOUTH, l2, -20, SOUTH, p);
        layout.putConstraint(EAST,  l2, -20, EAST,  p);
        p.add(l2);
    
        return p;
      }
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
        });
      }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new SpringScaleTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    }
    

提交回复
热议问题