关闭模式JComponent

时间:2019-03-14 15:26:28

标签: swing java-8 modal-dialog ubuntu-16.04 jcomponent

当我创建模式JComponent时,鼠标(正确)更改为默认光标。但是,当我关闭组件时,我遇到了一个奇怪的问题。

  • 如果在光标位于边界内时关闭组件 组件,光标将正确还原。
  • 如果我在光标超出界限(例如使用esc)时关闭组件,则即使调用setCursor(),光标也不会还原。

在两种情况下,如何以非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);
            }
        });
    }
}

0 个答案:

没有答案