Java Reference
In-Depth Information
Now we can figure out if enough space is available for displaying at least one of the images by
comparing the actual size with the image width and height. If one image fits, further tests are
performed to determine whether both images can fit in the space available. If so, the images are
arranged accordingly by setting the layout manager to a corresponding grid layout, and both images,
rect1 and rect2 , are added to the panel:
if (d.width >= width && d.height >= height) {
boolean dw = d.width >= 2 * width;
boolean dh = d.height >= 2 * height;
if (dw | dh) {
if ((dw && !dh) || (dw && dh && d.width > d.height))
setLayout (new GridLayout (1, 2));
else
setLayout (new GridLayout (2, 1));
add(rect1);
add(rect2);
}
If there is enough space for one image but not enough for both of them, only one is displayed,
depending on the state of a choice in the main frame. Also, the choice is enabled in order to let the user
select the component she would like to view:
else {
setLayout (new BorderLayout());
add(cardChoice.getSelectedIndex() == 0 ?
rect1 : rect2);
cardChoice.setEnabled (true);
}
}
Finally, if not even one image fits in the space available, we create a ScrollPane that contains the
two child components in a subpanel with a grid layout:
else {
setLayout (new BorderLayout());
ScrollPane scroll = new ScrollPane();
Panel panel = new Panel (new GridLayout (2, 1));
panel.add(rect1);
panel.add(rect2);
scroll.add(panel);
add(scroll);
}
super.doLayout();
}
For the case in which the application is running on a system with flexible window sizes, we need to add
a method returning the desired size of the dynamic panel. Here, the dimensions allowing a horizontal
arrangement of the child components are returned:
public Dimension getPreferredSize() {
return new Dimension (2 * width, height);
}
}
Listing 4.10 contains the code for the complete DynLayout example. The inner class
RectComponent is a custom component that is inserted into the DynPanel , showing the effects. It
 
Search WWH ::




Custom Search