Fire mouse event on base components

I am looking for a way to pass mouse events to components covered by other components. To illustrate what I mean, here is a sample code. It contains two JLabels, one of which is half the size and is completely covered with a larger label. If you hover over labels, only one of them fires the mouseEntered event.

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;

public class MouseEvtTest extends JFrame {

    public MouseEvtTest() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(null);
        setSize(250, 250);

        MouseAdapter listener = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.printf("Mouse entered %s label%n", e.getComponent().getName());
            }
        };
        LineBorder border = new LineBorder(Color.BLACK);

        JLabel smallLabel = new JLabel();
        smallLabel.setName("small");
        smallLabel.setSize(100, 100);
        smallLabel.setBorder(border);
        smallLabel.addMouseListener(listener);
        add(smallLabel);

        JLabel bigLabel = new JLabel();
        bigLabel.setName("big");
        bigLabel.setBorder(border);
        bigLabel.setSize(200, 200);
        bigLabel.addMouseListener(listener);
        add(bigLabel, 0); //Add to the front
    }

    public static void main(String[] args) {
        new MouseEvtTest().setVisible(true);
    }
}

What would be the best way to launch the entered mouse on a smaller label when the cursor moves to the coordinates above it? How will this work if several components were stacked on top of each other? What about the remaining mouse events like mouseClicked, mousePressed, mouseReleased etc.?

+3
source share
3
+2

:

bigLabel.dispatchEvent(mouseEvent);

, bigLabel final

+2

To understand what is going on, you need to understand how Z-Ordering works. As a brief overview of the component that was last added, it is first drawn. Therefore, in your case, you want to add a small component in front of a large component.

// add(bigLabel, 0); //Add to the front
add(bigLabel); // add to the end so it is painted first

OverlayLayout can help explain it better and give you another option.

0
source

Source: https://habr.com/ru/post/1725405/


All Articles