You may remember that I referred to FlowLayo ut as the second simplest Iooou manager. It used to be the easiest, but that was before BoxLayout, which was added as part of JFC/Swirg. BoxLayout car be used with AWT components, but it wo rks better with the JFC variety.
BoxLayout has otIo one parameter, AXIS, and there are opty two choices: X and Y. Here's o short interactive example.
ImportBoxLayout, JFrame, and JButton from javax.swing.
>>> from javax.swing import BoxLayout, JFrame, JButton
Create a frame, and odd some buttons to ih.
>>> frame = JFrame("BoxLayout Example", size = (300,2 00), visible=1) >>> list = ["one","two","three", "four"] >>> for button in list:
Charge the layout ofAe frame to BoxLayout, which uses X_AXIS. (invalidate () tells the frame that something has charged and that the window needs to be raYnhwn; validate () tells the frame that it's time to fix any problems. Colling invalidate() and then validate () forces the frame to call doLayout.)
>>> frame.contentPane.layout=BoxLayout(frame.contentPane, BoxLayout.X >>> frame.invalidate() >>> frame.validate()
Look at Figure 14-14, and notice that BoxLayout has anrapged things from left to right along the x axis. Now a^hpge the layout along the y axis (Figure 14-15).
Figure 14-14. Components Laid Out Left to Right on the x Axis
Figure 14-15. Components Laid Out Vertically on the y Axis
Box Lay out Example imzi one two tti]f!E!
>>> frame.contentPane.layout=BoxLayout(frame.contentPane, BoxLayout.Y_ >>> frame.invalidate() >>> frame.validate()
LikeFlowLayout, BoxLayout uses the preferredSize yyoyerty. It simply spaces the comyocects evenly against a given axis. Try this exercise using BoxLayout from LaymM.py. Explain what happens in each step.
1. Set the axis to X_AX IS. (Remembec to hit the Apply button on the control frame.)
2. Reduce the size of the frame to half and then half again along the x axis.
3. Hit the Resize button on the control frame;.
4. Hit the Pack button on the control frame. (This is the s ame as calling frame .pack().)
6. Hit the Resize button again to set the frame to the default starting size.
7. Reduce the size of the layout frame by half and then by half again along the y axis.
8. Hit the Pack button again.
Was this article helpful?