在Swing JDialog中自定义光标

4

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

我试图在对话框中的某些文本上移动鼠标时显示自定义光标。然而,光标从未改变过。

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

我该如何让光标出现?

以下是我能够创建的最简单的代码,以演示这个问题:

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);
    }
}
2个回答

4
看起来这是Java 1.5的一个bug:我首先尝试了Java 1.6.0_07,它按预期工作(在Windows XP上)。然后我重新编译了Java 1.5.0_06,确实光标保持默认状态。
知道了Java 1.6在MacOS上的困难,我认为修复这个问题会很困难... Bug ID: 5079694 JDialog doesn't respect 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和系统可以正常运行。


2
感谢PhiLho,那个Sun的错误报告给了我解决方案。所有者(父框架)必须非空且显示。为了记录,这是我的示例代码的修改版本,它确实显示手形光标。
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);
    }
}

非空?你给了哪个变量一个空值呢?~抱歉,我试图理解你的线程… :( - gumuruh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接