我有一个 Java Swing 应用程序,它是在 Mac OS X 10.5 上使用 Java 1.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 重新编译,确实光标保持在默认状态。
了解 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 和系统。
关于java - Swing JDialog 中的自定义光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/313916/