【发布时间】:2015-10-04 02:50:39
【问题描述】:
当使用 setCursor() 方法来更改组件使用的光标时,所有组件都可以正常工作,包括 JFrame 和 JDialog。
这里的问题在于 modal JDialog。当鼠标在对话框内部时,光标显示在右侧。但是,当鼠标移到对话框之外时,光标会重新设置为操作系统默认值,即使底层JFrame 使用与对话框相同的自定义光标。
我搜索了很多,找到了一些相关的问题,但没有一个正确答案。
我使用的是 Windows 10; JDK 1.8.0_40。
SSCCE:
package br.shura.knockback;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.*;
public class DialogCursorSSCCE extends JFrame {
public DialogCursorSSCCE() {
Cursor cursor = new Cursor(Cursor.CROSSHAIR_CURSOR);
JButton button = new JButton("Click me to open dialog.");
button.addActionListener(event -> {
JDialog dialog = new JDialog();
JLabel label = new JLabel("Move the mouse outside this dialog.");
int width = label.getFontMetrics(label.getFont()).stringWidth(label.getText());
label.setPreferredSize(new Dimension(width + 10, 50));
dialog.add(label);
dialog.pack();
dialog.setCursor(cursor);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.setTitle("Dialog");
dialog.setVisible(true);
});
button.setAlignmentX(CENTER_ALIGNMENT);
button.setMaximumSize(new Dimension(400, 100));
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(button);
setCursor(cursor);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
setTitle("DialogCursorSSCCE");
}
public static void main(String[] args) {
new DialogCursorSSCCE().setVisible(true);
}
}
【问题讨论】:
标签: java swing modal-dialog cursor jdialog