It appears that you didn't set the correct layer for the for the new layered Panel. I have included some code changes as well as suggestions. I am not an expert on JLayeredPane's so I can't really help much with that without do some testing of my own.
Regards,
Jim
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
// always a good idea
SwingUtilities.invokeLater(() -> new Frame());
}
}
//public class Frame extends JFrame {
// extending any class (especially JFrame) is not good practice unless you are
// overriding something. Use composition over inheritance when possible
class Frame {
JFrame frame = new JFrame(); // created the frame
MouseAdapter listener;
public Frame() {
// super.setSize(600, 600); probably ignored by layout manager
frame.setPreferredSize(new Dimension(600, 600));
// added the following so when you close the frame the app exits
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setSize(600, 600);
listener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Label1 was clicked");
JLabel label2 = new JLabel("LABEL 2");
JPanel panel2 = new JPanel();
panel2.setBackground(Color.RED);
panel2.setBounds(270, 0, 60, 60);
label2.setBounds(0, 0, 60, 60);
panel2.add(label2);
layeredPane.add(panel2, 0); // <-- changed from 2 to 0
label2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Label 2 was clicked.");
}
});
}
};
JPanel panel1 = new Panel(layeredPane);
JLabel label1 = new JLabel("LABEL 1");
label1.setBounds(0, 0, 60, 60);
panel1.add(label1);
label1.addMouseListener(listener);
layeredPane.add(panel1, 1);
frame.add(layeredPane);
// super.validate();
frame.pack(); // read API for description
frame.setLocationRelativeTo(null); // centers on screen - check API
frame.setVisible(true); // removed from Main
}
}
class Panel extends JPanel {
JLayeredPane layeredPane;
// Instead of extending JPanel which serves no purpose
// why not make a method in Frame.java that simply creates a
// layeredPane, and adds a JLabel, text, and mouse listener
// and then returns the layeredPane
public Panel(JLayeredPane layeredPane) {
this.layeredPane = layeredPane;
// super.setSize(600, 600); not needed
// super.setBounds(0, 0, 60, 60);
setBounds(270, 0, 60, 60);// methods are inherited - super not required
super.setBackground(Color.BLUE);
}
}