问题描述
即使jdialog不在焦点上,也可以保留设置的鼠标光标吗?
我有以下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);
}
});
}
}
这是正在发生的事情:
我的目标是即使jdialog不在焦点上,也可以将调整大小的光标保留在鼠标悬停上。
在MacOS Catalina 10.15.4上采用AdoptOpenJDK 11和15以及Liberica JDK 11进行了尝试
解决方法
为对话框添加鼠标侦听器。通过使用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());
}
});