[英]Why does a JButton under a JPanel still react?
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. 我有一个JLayeredPane,在那里有2个JPanels。 The deepest one ( furthest down ) has JButtons on there. 最深的一个(最下面)有JButton。 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. 现在,当我将鼠标悬停在我的JButtons(后面是另一个JPanel)上时,它们仍会向我添加到它们的MouseListener激活事件。 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. 在这里,我将两个面板添加到分层窗格,这指的是扩展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 这里指的是最底层的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. 这个游戏的目的是一个名为gipf的游戏,我使用的布局是绝对的,因为很难将所有内容对齐成六边形。
Now when I hover over my JButtons ( which are behind the other JPanel ), they still fire events to the MouseListener I added to them 现在,当我将鼠标悬停在我的JButtons(后面是另一个JPanel)上时,它们仍会向我添加到它们的MouseListener激发事件
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. 当生成需要传递给组件的事件时,Swing从父/子层次结构的底部搜索到顶部,直到找到想要处理该事件的组件。
What can I do to make it stop? 我该怎么办才能让它停下来?
Add a MouseMotionListener
to the top panel to intercept events like mouseEntered/mouseExited. 将MouseMotionListener
添加到顶部面板以拦截mouseEntered / mouseExited等事件。 This way you will still be able to handle button clicks in the other panel. 这样,您仍然可以在其他面板中处理按钮点击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.