Java Reference
In-Depth Information
The most important method is layoutContainer() . This method needs to examine all the
components and decide where to put them and how big to make each one. Having made the
decision, it can use setBounds() to set each one's position and size.
Other than a bit of error checking, that's all that's involved. Here's an example, EntryLay-
out , that implements the multicolumn layout shown in Figure 14-18 . Quoting its javadoc
documentation:
A simple layout manager, for Entry areas like:
Login: __
Password: __
Basically two (or more) columns of different, but constant, widths.
Construct instances by passing an array of the column width percentages (as doubles, fractions
from 0.1 to 0.9, so 40%, 60% would be {0.4, 0.6}). The length of this array uniquely determines
the number of columns. Columns are forced to be the relevant widths. As with GridLayout, the
number of items added must be an even multiple of the number of columns. If not, exceptions
may be thrown!
First, let's look at the program that uses this layout to produce Figure 14-18 . This program
simply creates a JFrame , gets the contentPane container, and sets its layout to an instance
of EntryLayout , passing an array of two double s representing the relative widths (decimal
fractions, not percentages) into the EntryLayout constructor. Then we add an even number
of components, and call pack() —which in turn calls our preferredLayoutSize() —and
setVisible(true) :
public
public class
class EntryLayoutTest
EntryLayoutTest {
/** "main program" method - construct and show */
public
public static
void main ( String [] av ) {
testTwoCols ();
testFiveCols ();
static void
}
static
static void
void testTwoCols () {
final
final JFrame f = new
new JFrame ( "EntryLayout Demonstration" );
Container cp = f . getContentPane ();
double
double widths [] = { . 33 , . 66 };
cp . setLayout ( new
new EntryLayout ( widths ));
cp . add ( new
new JLabel ( "Login:" , SwingConstants . RIGHT ));
cp . add ( new
new JTextField ( 10 ));
Search WWH ::




Custom Search