[英]How to retain assigned cursor to JDialog even on lost focus?
Is there a way to retain the set mouse cursor even the JDialog is not in focus?即使 JDialog 不在焦点上,有没有办法保留设置的鼠标光标?
I have the following SSCCE:我有以下 SSCCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JDialog {
public Test() {
super((Frame) null, true);
setLayout(new BorderLayout());
setModalityType(Dialog.ModalityType.MODELESS);
setType(Window.Type.UTILITY);
setUndecorated(true);
setAlwaysOnTop(true);
setBackground(Color.BLACK);
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
getContentPane().setBackground(Color.BLACK);
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
setLocationRelativeTo(null);
var label = new JLabel("Focused");
label.setForeground(Color.WHITE);
addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
label.setText("Focused");
}
@Override
public void windowLostFocus(WindowEvent e) {
label.setText("Not Focused");
}
});
add(label, BorderLayout.CENTER);
}
public static void main(String[] args) {
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Test sw = new Test();
// Display the window.
sw.setVisible(true);
}
});
}
}
Here is what is happening:这是正在发生的事情:
My goal is for the resize cursor to be retained on mouse hover even if the JDialog is not focused.我的目标是在鼠标悬停时保留调整大小的光标,即使 JDialog 没有聚焦。
Tried on AdoptOpenJDK 11 & 15 and Liberica JDK 11 on MacOS Catalina 10.15.4在 MacOS Catalina 10.15.4 上尝试了 AdoptOpenJDK 11 & 15 和 Liberica JDK 11
Add a mouse listener for your dialog.为您的对话框添加一个鼠标侦听器。 By using the MouseAdapter implementation, you can override only the methods that you want.
通过使用 MouseAdapter 实现,您可以仅覆盖所需的方法。
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
setCursor(Cursor.getDefaultCursor());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.