OverlayLayout Manager Example Java Swing

OverlayLayout Manager Example Java Swing

We have seen earlier BoxLayout manager where the components are set in X and Y axes directions. Now let us go for another exclusive Swing manager, OverlayLayout.

As the name indicates, one component can be placed on the top of the another. When different sizes are given, the components can be all be seen. User can interact with anyone you would like. This may be little confusing right now; first see the one of the output screens given below. You may have clarity over this layout manager.

To align the components, over the other or anywhere in on the frame, there comes two methods setAlignmentX() and setAlignmentY(). The parameters are floating values ranging 0.0f to 1.0f. If you give more than 1.0f, it it not an error and takes the maximum 1.0f by default.

In the following OverlayLayout program, alignments are not set and components take the default as 0.0f.

OverlayLayout

Alignment for the 3 buttons can be set to place them where we would like in the JFrame. When not set, the button takes 0.0f as follows.

btn1.setAlignmentX(0.0f);
btn1.setAlignmentY(0.0f);

In the program, the alignment for all the three buttons btn1, btn2 and btn3, can be set as follows:

btn1.setAlignmentX(0.5f);
btn1.setAlignmentY(0.5f);

When set for all the three buttons, the following is output.

OverlayLayout

After 0.0f and 0.5f, let us use the maximum 1.0f and observe the output.

btn1.setAlignmentX(1.0f);
btn1.setAlignmentY(1.0f);

OverlayLayout

Leave a Reply

Your email address will not be published. Required fields are marked *