< 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.
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 > |