开发者

Detect mouse click anywhere on window

I've written a JWindow that acts a bit like a fancy menu in my application, popping up when a button is pressed. However, I'd like it to disappear if the user clicks anywhere in the main window. I can of course add a mouse listener to the main window, but that doesn't add it to all the components on the window itself, and looping over all the components seems like a bit of a brute force solution (and can't be guaranteed to work if the components on the window change.)

What's the best way of going about doing so开发者_开发问答mething like this?


Try to use Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask). Find eventMask that filters only mouse clicks. This AWT listener is global for whole application, so you can see all events that happen.


I'd like it to disappear if the user clicks anywhere in the main window

Add a WindowListener to the child window and then handle the windowDeactiveated() event and invoke setVisible(false) on the child window.

Working example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DialogDeactivated
{
    public static void main(String[] args)
    {
        final WindowListener wl = new WindowAdapter()
        {
            public void windowDeactivated(WindowEvent e)
            {
                e.getWindow().setVisible(false);
            }
        };

        JButton button = new JButton("Show Popup");
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                JButton button = (JButton)e.getSource();
                JFrame frame = (JFrame) SwingUtilities.windowForComponent(button);

                JDialog dialog = new JDialog(frame, false);
                dialog.setUndecorated(true);
                dialog.add( new JButton("Dummy Button") );
                dialog.pack();
                dialog.setLocationRelativeTo( frame );
                dialog.setVisible( true );
                dialog.addWindowListener( wl );
            }
        });

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(button, BorderLayout.NORTH);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜