Swing JDialog中的自定义光标

我有一个Java Swing应用程序,使用Java 1.5在Mac OS X 10.5上开发。

当用户将鼠标移到对话框中的某些文本上时,我正在尝试使用自定义光标。 但是,光标永远不会改变。

当我不使用JFrame而不是JDialog时,光标确实会改变。 但是我必须自己编写所有的对话框代码。

如何让光标出现?

这是我可以创建的最简单的代码来演示问题:

import javax.swing.*; import java.awt.*; public class CursorTest { public static void main(String[] args) { JLabel label = new JLabel("Move mouse here for hand cursor"); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); JOptionPane pane = new JOptionPane(label); pane.setOptions(new Object[]{"OK"}); JDialog dialog = pane.createDialog(null, "Test Dialog"); dialog.setVisible(true); } } 

看起来它是Java 1.5中的一个错误:我首先尝试使用Java 1.6.0_07并且它按预期工作(在Windows XP上)。 然后我用Java 1.5.0_06重新编译,实际上光标仍处于默认状态。

知道MacOS上Java 1.6的困难,我发现很难解决这个问题……

错误ID:5079694 JDialog不尊重setCursor
他们给出了解决方法……

[编辑]经过测试的解决方法:

 public class CursorTest extends JFrame { private CursorTest() { } private void ShowDialog() { JLabel label = new JLabel("Move mouse here for hand cursor"); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); JOptionPane pane = new JOptionPane(label); pane.setOptions(new Object[] { "OK" } ); JDialog dialog = pane.createDialog(this, "Test Dialog"); dialog.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { CursorTest testFrame = new CursorTest(); testFrame.setTitle("Test GUI"); testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); testFrame.setSize(500, 300); testFrame.setVisible(true); testFrame.ShowDialog(); } }); } } 

适用于我的JDK和系统。

感谢PhiLho,Sun bug报告给了我解决方案。 所有者(父框架)必须为非null并显示。 为了记录,这里是我的示例代码的修改版本,它确实显示了手形光标。

 import javax.swing.*; import java.awt.*; public class CursorTest { public static void main(String[] args) { JLabel label = new JLabel("Move mouse here for hand cursor"); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); JOptionPane pane = new JOptionPane(label); pane.setOptions(new Object[]{"OK"}); JFrame parent = new JFrame(); parent.setVisible(true); JDialog dialog = pane.createDialog(parent, "Test Dialog"); dialog.setModal(false); dialog.setVisible(true); } } 
Interesting Posts