Why does a JButton under a JPanel still react?

£可爱£侵袭症+ 提交于 2021-02-10 03:24:15

问题


I looked around for my problem, and i couldn't find an answer, so here I go:

I have a JLayeredPane, and in there there are 2 JPanels. The deepest one ( furthest down ) has JButtons on there. The second one ( The one on top ) has a partially transparent background color ( although i don't think this should influence it ).

Now when I hover over my JButtons ( which are behind the other JPanel ), they still fire events to the MouseListener I added to them. I don't know why...

Why is this the case? What can I do to make it stop?

Here I add both the panels to the layered pane, and this refers to my class which extends a JFrame.

    JLayeredPane layer = this.getLayeredPane();
    layer.removeAll();

    this.gamePanel = new GamePanel(game);


    this.ghostPanel = new GhostPanel();
    this.ghostPanel.setOpaque(true);
    this.ghostPanel.setVisible(true);

    layer.add(this.gamePanel, new Integer(0));
    layer.add(this.ghostPanel, new Integer(1));

Here I have some buttons ( with an absolute layout ) added to the lowest panel

    this.setLayout(null);
    for (int j = 0; j < 5; j++) {
        for (int i = 0; i < 5 + j; i++) {
            this.add(this.buttons[i][j]);
        }
    }
    for (int j = 1; j < 5; j++) {
        for (int i = j; i < 9; i++) {
            this.add(this.buttons[i][4 + j]);
        }
    }

Here this refers to the most bottom JPanel

The purpose of this is a game called gipf, and the layout I went with is absolute because it was very hard to align everything in a hexagonal shape.


回答1:


Now when I hover over my JButtons ( which are behind the other JPanel ), they still fire events to the MouseListener I added to them

When an event is generated in needs to be passed to a component, so Swing searches from the bottom of the parent/child hierarchy to the top until it finds a component that wants to handle the event.

What can I do to make it stop?

Add a MouseMotionListener to the top panel to intercept events like mouseEntered/mouseExited. This way you will still be able to handle button clicks in the other panel.



来源:https://stackoverflow.com/questions/32893810/why-does-a-jbutton-under-a-jpanel-still-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!