如何在被打开的JDialog阻止的窗口上捕捉鼠标点击事件



简单地说,我想要的是在被模式JDialog阻止的窗口上点击鼠标。

这里有一个例子:

public class BlockedFrameTest
{
public static void main ( final String[] args )
{
Toolkit.getDefaultToolkit ().addAWTEventListener ( new AWTEventListener ()
{
@Override
public void eventDispatched ( final AWTEvent event )
{
if ( event instanceof MouseEvent )
{
System.out.println ( event );
}
}
}, AWTEvent.MOUSE_EVENT_MASK );
final JFrame frame = new JFrame ( "Frame" );
frame.add ( new JLabel ( "Content" )
{
{
setBorder ( BorderFactory.createEmptyBorder ( 100, 100, 100, 100 ) );
}
} );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setVisible ( true );
final JDialog dialog = new JDialog ( frame, "Dialog" );
dialog.setModal ( true );
dialog.add ( new JLabel ( "Content" )
{
{
setBorder ( BorderFactory.createEmptyBorder ( 50, 50, 50, 50 ) );
}
} );
dialog.pack ();
dialog.setLocationRelativeTo ( frame );
dialog.setVisible ( true );
}
}

通过查看示例输出日志,您将看到当打开JDialog时,JFrame中的事件不会传递(甚至不会传递到示例中添加的全局AWT事件侦听器中)。

所以我想知道,有没有什么方法可以捕捉到被阻止的JFrame上的点击
或者至少在用户"触摸"被阻止的东西时捕捉到一个事件?

我需要这个的原因是当这样的事件发生时,使自定义装饰的JDialog blick。

也许这有帮助:

如何在Java 中获取窗口外的鼠标点击坐标

这有点困难,因为您要离开Swing领域,进入本机GUI域。

如果您的JDialog是模态的,我认为您无法做到这一点,但您可以使用FocusListener的下一个技巧:

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Example {
public static void main(final String[] args) {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "Dialog");
frame.add(new JLabel("Content") {
{
setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
}
});
frame.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
System.out.println("frame pressed");
System.out.println("dialog focused " + dialog.isFocused());
System.out.println("frame focused " + frame.isFocused());
super.mousePressed(arg0);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

dialog.add(new JLabel("Content") {
{
setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
}
});
dialog.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent arg0) {
super.focusLost(arg0);
dialog.requestFocus();
}
});
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
}

输出:

frame pressed
dialog focused true
frame focused false

相关内容

  • 没有找到相关文章

最新更新