Michael Berry
Michael Berry

Reputation: 72399

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 something like this?

Upvotes: 4

Views: 5401

Answers (2)

camickr
camickr

Reputation: 324207

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 );
     }
}

Upvotes: 3

AlexR
AlexR

Reputation: 115398

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.

Upvotes: 6

Related Questions