0

我一直在尝试创建的效果是,只要鼠标进入 JPanel 上的某个区域,鼠标光标图标就会发生变化,而只要它离开该区域,就会切换到默认值。我在 MouseMotionListener 类中使用 MouseMoved 功能,每当鼠标在 JPanel 上移动时,它都会验证坐标是否对应于特殊区域。

但是,这种方法对计算机处理器的压力非常大,所以我想问一下是否有更有效的方法。任何帮助表示赞赏。

What the program does is it draws figures on a JPanel, and when the Connection button is selected then it connects those figures with a line if the user clicks on one figure, and then on another.

这些图形绘制在 JPanel 上,并存储了它们各自的区域边界,因此当鼠标移动时,它会检查当前 X 和 Y 坐标是否在这些区域之一内,如果是,则更改光标。checkValidConnectionRegion 检查当前 X 和 Y 变量是否在图形区域内。这是处理程序的代码:

public void mouseMoved(MouseEvent e)
    {
        if(GUI.Connectionbutton.isSelected())
        {
            x = e.getX();
            y = e.getY();

            checkValidConnectionRegion(); 

            if(validConnectionRegion)
                setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
            if(!validConnectionRegion)
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }
4

3 回答 3

5

一种更有效的方法是JPanel在 parent中添加一个 child JPanel,这将充当不可见区域。然后只需将光标设置在孩子JPanel身上,当您移过它时,鼠标指针应该会发生变化。

JPanel mainPnl = new JPanel(new BorderLayout());

JPanel invisibleArea = new JPanel();
invisibleArea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
invisibleArea.setPreferredSize(new Dimension(100, 100));

mainPnl.add(invisibleArea, BorderLayout.WEST);
于 2009-08-26T07:19:14.290 回答
2

您可能在 MouseMoved 处理程序中运行效率低下的代码。

您可以发布 MouseMoved 处理程序的全部源代码吗?

于 2009-08-26T05:13:38.350 回答
2

我不熟悉Java,但问题可能是Cursor.getPredefinedCursor每次调用它时都会创建一个新的游标实例。(不知道是不是真的)

尝试final在你的类中为两个光标创建两个字段,并且只设置一次。

validConnectionRegion此外,如果实际更改,请尝试仅设置光标。

例如:

final Cursor crosshairCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
final Cursor defaultCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);

public void mouseMoved(MouseEvent e)
{
    if(GUI.Connectionbutton.isSelected())
    {
        x = e.getX();
        y = e.getY();

        boolean wasValid = validConnectionRegion;
        checkValidConnectionRegion(); 

        if(wasValid != validConnectionRegion)
            setCursor(validConnectionRegion ? crosshairCursor : defaultCursor);
    }
}
于 2009-08-26T20:26:11.737 回答