Java Swing GUI

JLayeredPane – Java Swing – Example

In this tutorial, we are going to see an example of JLayeredPane in Java Swing. JLayeredPane class is used to overlay components. It is used to provide a third dimension for component positioning and divide the depth range into several different layers.
 

Constructors of JLayeredPane class:
  • JLayeredPane() : It is used to create a new JLayeredPane.

 

Commonly used methods:
  • getIndexOf(Component c) : It is used to return the index of the specified component.
  • getLayer(Component c) : It is used to return the layer attribute for the specified component.
  • getPosition(Component c) : It is used to return the relative position of the component in its layer.
 

Example of JLayeredPane in Java Swing
import javax.swing.*;
import java.awt.*;

public class MyJLayeredPane extends JFrame 
{
  public MyJLayeredPane() 
  {
     setSize(200, 200);
     JLayeredPane pane = getLayeredPane();
	 
     //Create buttons
     JButton btn1 = new JButton();
     btn1.setBackground(Color.yellow);
     btn1.setBounds(30, 30, 60, 60);
	 
     JButton btn2 = new JButton();
     btn2.setBackground(Color.orange);
     btn2.setBounds(50, 50, 60, 60);
	 
     JButton btn3 = new JButton();
     btn3.setBackground(Color.red);
     btn3.setBounds(70, 70, 60, 60);
	 
     //Add buttons to the panel by specifying the order
     pane.add(btn3, new Integer(1));
     pane.add(btn2, new Integer(2));
     pane.add(btn1, new Integer(3));
  }
  public static void main(String[] args) 
  {
      MyJLayeredPane frame = new MyJLayeredPane();
      frame.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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