Doing without a Layout Manager (Absolute Positioning)

 <  Day Day Up  >  

Although you can do without one, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances , to different font sizes, to a container's changing size , and to different locales. It can also be reused easily by other containers as well as other programs.

Still, if a container holds components whose size isn't affected by the container's size or by font and look-and-feel and language changes, absolute positioning might make sense. Desktop panes, which contain internal frames, are in this category. The size and position of the frames don't depend directly on the pane's size. Instead, the programmer determines their initial size and placement, and then the user can move or resize them. A layout manager is unnecessary in this situation. Absolute positioning might also make sense for a custom container that performs size and position calculations that are particular to it and that perhaps require knowledge of its specialized state. This is the situation with split panes. Figure 11 is an example of absolute positioning.

Figure 11. A frame whose content pane uses absolute positioning.

graphics/04fig11.gif

graphics/cd_icon.gif

You can run AbsoluteLayoutDemo using Java Web Start or compile and run the example yourself. [8]

[8] To run AbsoluteLayoutDemo using Java Web Start, click the AbsoluteLayoutDemo link on the RunExamples/layout.html page on the CD. You can find the source files here: JavaTutorial/uiswing/layout/example-1dot4/index.html#AbsoluteLayoutDemo .

The code snippet that follows shows how the components in the content pane are created and laid out:

 pane.setLayout(null); JButton b1 = new JButton("one"); JButton b2 = new JButton("two"); JButton b3 = new JButton("three"); pane.add(b1); pane.add(b2); pane.add(b3); Insets insets = pane.getInsets(); Dimension size = b1.getPreferredSize(); b1.setBounds(25 + insets.left, 5 + insets.top,              size.width, size.height); size = b2.getPreferredSize(); b2.setBounds(55 + insets.left, 40 + insets.top,              size.width, size.height); size = b3.getPreferredSize(); b3.setBounds(150 + insets.left, 15 + insets.top,              size.width + 50, size.height + 20); ...//In the main method: Insets insets = frame.getInsets(); frame.setSize(300 + insets.left + insets.right,               125 + insets.top + insets.bottom); 
 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net