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.
public class OverlayLayoutExample extends JFrame
JButton btn1, btn2, btn3;
Container c = getContentPane();
p1 = new JPanel();
OverlayLayout overlay = new OverlayLayout(p1);
btn1 = new JButton("OK");
Dimension d1 = new Dimension(75, 50);
btn2 = new JButton("RETRY");
Dimension d2 = new Dimension(125, 75);
btn3 = new JButton("CANCEL");
Dimension d3 = new Dimension(150, 100);
public static void main(String args)
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.
In the program, the alignment for all the three buttons btn1, btn2 and btn3, can be set as follows:
When set for all the three buttons, the following is output.
After 0.0f and 0.5f, let us use the maximum 1.0f and observe the output.