Start by having a closer look at How to Use Layered Panes. You need to specify the layer you want each component to reside, otherwise they will overlap each other
Just in case you miss it, they key factor here is the use of JLayeredPane#setLayer
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class TestLayer {
public static void main(String[] args) {
new TestLayer();
}
public TestLayer() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JLayeredPane {
public TestPane() {
setLayout(new GridBagLayout());
ColorPane background = new ColorPane(Color.WHITE) {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
ColorPane foreground = new ColorPane(Color.BLACK) {
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(background, gbc);
setLayer(background, 0);
add(foreground, gbc);
setLayer(foreground, 1);
}
@Override
public void doLayout() {
super.doLayout();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public class ColorPane extends JPanel {
public ColorPane(Color backGround) {
setBackground(backGround);
setBorder(new LineBorder(Color.RED));
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
setBackground(Color.RED);
}
@Override
public void mouseReleased(MouseEvent e) {
setBackground(backGround);
}
});
}
}
}
}