gpt4 book ai didi

Java JLayeredPane 覆盖光标

转载 作者:行者123 更新时间:2023-12-01 12:53:04 26 4
gpt4 key购买 nike

我有一个多层 java 应用程序,其中包含一系列需要手形光标的 JLabel 按钮,例如:

button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); 

但是,我上面有一个层,其边界覆盖整个应用程序(用于绘制弹出窗口等)。现在我已经添加了上面的图层,我的光标不再改变。我尝试将上面图层的光标设置为空,但没有任何影响。

这是图层的基本布局:

private void create() {
this.addWindowListener(windowAdapter);
this.setLayout(new BorderLayout());

layers = new JLayeredPane();
layers.setPreferredSize(this.getSize());

dashboard = new DashBoard.DashBoardLayer();
dashboard.setBounds(0, this.getHeight()-275, this.getWidth(),275);

application = new App.ApplicationLayer();
application.setBounds(0,0,this.getWidth(),this.getHeight()-145);

filter = new FilterLayer();
filter.setBounds(0,195,this.getWidth(),490);

menuBG = MenuLayerBg.getInstance();
menuBG.setBounds(0,0,this.getWidth(),this.getHeight());

menuPanes = MenuLayer.getInstance();
menuPanes.setBounds(0,0,this.getWidth(),this.getHeight());

layers.add(application, new Integer(0));
layers.add(filter, new Integer(1));
layers.add(dashboard, new Integer(2));
layers.add(menuBG, new Integer(3));
layers.add(menuPanes, new Integer(4));

this.add(layers, BorderLayout.CENTER);
}

最佳答案

MouseEvent 仅被分派(dispatch)到顶部的组件。因此,如果顶层完全覆盖底层的组件,它们将不会收到 MouseEvent。

查看 How to Use Layered Panes 上 Swing 教程中的 LayeredPaneDemo.java 代码。我对代码进行了以下更改:

    for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i],
layerColors[i], origin);
layeredPane.add(label, new Integer(i));
origin.x += offset;
origin.y += offset;

label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // added
}

每个组件的大小固定小于整个框架,因此事件将被顶部组件下方的组件接受。

当您运行代码时,光标将在顶部两个标签上发生变化。

如果将“Dukes Layer and Position”更改为“Yellow”并取消选中该复选框,则所有标签的光标都会发生变化。

However, I have a layer above that has bounds covering the entire application

一种可能的解决方案是将鼠标事件“重新分派(dispatch)”到顶层以下的组件。有关此方法的示例,请查看 How to Use Root Panes 上 Swing 教程中的 GlassPaneDemo.java

或者对于完全不同的方法,您可以尝试重写组件的 contains(...) 方法以始终返回 false。这样,鼠标事件将永远不会被分派(dispatch)到您的组件,因为鼠标点不属于该组件。我以前从未尝试过,所以我不知道这是否会导致其他问题。

我在 LayeredPaneDemo 中尝试了这一点,将以下内容更改为 createColoredLabel(...) 方法:

    JLabel label = null;

if (color.equals(Color.green))
{
label = new JLabel(text)
{
@Override
public boolean contains(int x, int y)
{
return false;
}
};
}
else
label = new JLabel(text);

//JLabel label = new JLabel(text);

关于Java JLayeredPane 覆盖光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24070864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com