Global Event Listeners with AWTEventListener & how to pull MouseEvent's from it

前端 未结 2 1001
猫巷女王i
猫巷女王i 2020-12-16 06:39

The following question is based on the following information. Scroll down to see the actual question - it refers to the console output specifically.

I have stripped

2条回答
  •  难免孤独
    2020-12-16 06:54

    code for correct suggestion by @StanislavL

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    class ClosingFrame extends JFrame {
    
        private static final long serialVersionUID = 1L;
        private AWTEventListener awt;
    
        public ClosingFrame() {
            setName("Dialog ... ClosingFrame");
            JButton b = new JButton("close dialog.  
    enter this button from
    " + "the top to get the
    hoverhelp close enough
    to cause problems"); b.setName("buttonToPress"); b.setToolTipText("111111111111111111111" + "1111111111111111111111111111111111111111111
    "); b.addActionListener(closeActionListener); add(b); JPopupMenu menu = new JPopupMenu(); menu.add("some item ..........."); menu.add("another one .........."); b.setComponentPopupMenu(menu); pack(); setVisible(true); } private AWTEventListener createAWTWindowListener() { AWTEventListener awt1 = new AWTEventListener() { @Override public void eventDispatched(AWTEvent e) { if (MouseEvent.MOUSE_EXITED == e.getID()) { MouseEvent event = (MouseEvent) e; String name = event.getComponent().getName(); System.out.println("got mouseExited: " + name); awtMouseExited(event); } } }; return awt1; } private void awtMouseExited(MouseEvent event) { Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), this); if (!getBounds().contains(point)) { // if (!getRootPane().getVisibleRect().contains(point)) { dispose(); } } private void installHoverListeners() { if (awt != null) { return; } awt = createAWTWindowListener(); Toolkit.getDefaultToolkit().addAWTEventListener(awt, AWTEvent.MOUSE_EVENT_MASK); } private void uninstallHoverListeners() { if (awt == null) { return; } Toolkit.getDefaultToolkit().removeAWTEventListener(awt); awt = null; } @Override public void addNotify() { super.addNotify(); installHoverListeners(); } @Override public void removeNotify() { uninstallHoverListeners(); super.removeNotify(); } private ActionListener closeActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { dispose(); } }; public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ClosingFrame closingFrame = new ClosingFrame(); } }); } }

提交回复
热议问题