What is the importance of OverlayLayout in Java?


OverlayLayout

  • An OverlayLayout is a subclass of Object class and it can arrange the components over the top of each other and uses components specified alignments to position them relatively.
  • When different sizes are given to any of the components, we can see all the components.
  • To align the components over the other or anywhere in the frame, we can use two methods setAlignmentX() and setAlignmentY(). The parameters are floating values ranging from 0.0f to 1.0f. An OverlayLayout takes the maximum 1.0f by default.
  • The important methods of an OverlayLayout are addLayoutComponent(), getTarget(), invalidateLayout(), maximumLayoutSize() and etc.

Example

import java.awt.*;
import javax.swing.*;
import javax.swing.OverlayLayout;
public class OverlayLayoutTest extends JFrame {
   public OverlayLayoutTest() {
      setTitle("OverlayLayout Test");
      JPanel panel = new JPanel() {
         public boolean isOptimizedDrawingEnabled() {
            return false;
         }
      };
      LayoutManager overlay = new OverlayLayout(panel);
      panel.setLayout(overlay);
      JButton button = new JButton("Small");
      button.setMaximumSize(new Dimension(75, 50));
      button.setBackground(Color.white);
      panel.add(button);
      button = new JButton("Medium Btn");
      button.setMaximumSize(new Dimension(125, 75));
      button.setBackground(Color.lightGray);
      panel.add(button);
      button = new JButton("Large Button");
      button.setMaximumSize(new Dimension(200, 100));
      button.setBackground(Color.orange);
      panel.add(button);
      add(panel, BorderLayout.CENTER);
      setSize(400, 300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }  
   public static void main(String args[]) {
      new OverlayLayoutTest();
   }
}

Output

Updated on: 10-Feb-2020

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements