当我创建模式JComponent时,鼠标(正确)更改为默认光标。但是,当我关闭组件时,我遇到了一个奇怪的问题。
在两种情况下,如何以非hacky方式正确恢复光标?
示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
class ModalTest {
public static void main (String[] args) {
// Create a frame.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
// Add a button.
JButton button = new JButton();
frame.add(button);
frame.revalidate();
frame.setVisible(true);
frame.setCursor(Cursor.HAND_CURSOR);
// While the mouse is inside the JFrame, the cursor should be Cursor.HAND_CURSOR.
// And when the modal JOptionPane is visible, the cursor should be Cursor.DEFAULT_CURSOR.
// However, when that modal JComponent is closed while the cursor is outside it, it does
// not revert to Cursor.HAND_CURSOR.
button.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showConfirmDialog (
frame,
"Move the cursor inside, then outside of this component and press Esc. The cursor will stay default.",
"Cursor Test",
JOptionPane.YES_NO_OPTION
);
// Even if you change the cursor after, it stays default.
frame.setCursor(Cursor.CROSSHAIR_CURSOR);
}
});
}
}