为什么 setCursor() 不起作用?

Why is setCursor() not working?

我正在通过尝试为我的游戏制作自定义光标来测试 java 的一个新方面,但似乎 运行 我的代码 [=16] 遇到了问题=]setCursor(); 引发编译器错误,因为它不被视为一段正确的代码。我一直在关注教程和不同的指南,它们都导致了同样的问题,但我没有找到查询的答案。

Toolkit toolKit = Toolkit.getDefaultToolkit();
Image img = toolKit.getImage(getClass().getResource("/res/cursor.png"));
Point point = new Point(0, 0);
Cursor cursor = toolKit.createCustomCursor(img, point, "Cursor");
setCursor(cursor);

希望有人能帮助我,在此先感谢。 备注:

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: The method setCursor(Cursor) is undefined for the type Main

感谢 MadProgrammer 最后的评论,问题已解决:

Then, you need to call setCursor with the instance of JPanel - A runnable example would make it easier.

我遇到的问题是我使用了 JFrame 作为我的容器,而不是 JPanel。为了修复我以前的代码,我将我的主容器更改为 JPanel,它在 return 中允许我使用:JPanelName.setCursor();

编辑:通过进一步测试,我还发现 JFrame 仍然可以像前面提到的那样使用。我上面的代码的问题是我将它作为 JFrame.setCursor(); 调用,这是对非静态方法的静态调用。这给我的印象是我应该只使用 setCursor(); (如我上面的查询所示)。希望这对可能对 setCursor(); 方法有一些误解的任何人有所帮助。再次感谢 MadProgrammer 解决问题