为什么JPanel下的JButton仍会做出反应? [英] Why does a JButton under a JPanel still react?

查看:55
本文介绍了为什么JPanel下的JButton仍会做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,但找不到答案,所以我去了:

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

我有一个JLayeredPane,其中有2个JPanels. 最深的(最远的)上面有JButton. 第二个(顶部的一个)具有部分透明的背景颜色(尽管我认为这不会影响它).

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 ).

现在,当我将鼠标悬停在JButton(位于另一个JPanel的后面)上时,它们仍然会向我添加到它们的MouseListener触发事件.我不知道为什么...

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?

在这里,我将两个面板都添加到分层窗格中,这是指我的类扩展了JFrame.

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]);
        }
    }

这里指的是最底层的JPanel

Here this refers to the most bottom JPanel

此游戏的目的是一款名为gipf的游戏,我使用的布局是绝对的,因为很难将所有内容对齐为六角形.

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.

推荐答案

现在,当我将鼠标悬停在JButton(位于另一个JPanel的后面)上时,它们仍然会向我添加到它们的MouseListener触发事件

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

在中生成事件时,需要将其传递给组件,因此Swing从父/子层次结构的底部搜索到顶部,直到找到要处理该事件的组件为止.

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?

在顶部面板中添加MouseMotionListener以拦截诸如mouseEntered/mouseExited之类的事件.这样,您仍然可以处理其他面板中的按钮单击.

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.

这篇关于为什么JPanel下的JButton仍会做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆