How can I align all elements to the left in JPanel?

前端 未结 3 1077
误落风尘
误落风尘 2020-12-14 05:42

I would like to have all elements in my JPanel to be aligned to the left. I try to do it in the following way:

JPanel panel = new JPanel();
panel.setLayout(n         


        
相关标签:
3条回答
  • 2020-12-14 06:31

    My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.

    //To align it to the left
    p.add(b, BorderLayout.WEST);
    
    //To align it to the right
    p.add(b, BorderLayout.EAST);
    
    //To align it at the top
    p.add(b, BorderLayout.NORTH);
    
    //To align it to the bottom
    p.add(b, BorderLayout.SOUTH);
    
    //To align it to the center
    p.add(b, BorderLayout.CENTER);
    

    Don't forget to import it as well by typing:

    import java.awt.BorderLayout;
    

    There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!

    0 讨论(0)
  • 2020-12-14 06:33

    The easiest way I've found to place objects on the left is using FlowLayout.

    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    

    adding a component normally to this panel will place it on the left

    0 讨论(0)
  • 2020-12-14 06:34

    You should use setAlignmentX(..) on components you want to align, not on the container that has them..

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(c1);
    panel.add(c2);
    
    c1.setAlignmentX(Component.LEFT_ALIGNMENT);
    c2.setAlignmentX(Component.LEFT_ALIGNMENT);
    
    0 讨论(0)
提交回复
热议问题