Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 43

Thread: close JPopupMenu after focus lost

  1. #1

    Default close JPopupMenu after focus lost

    i have JPopupMenu and i need when mouse click outside of JPopupMenu my popup is closed
    this is my code but focusLost not working
    final JPopupMenu popup = new JPopupMenu();
     
    public void mouseClicked(MouseEvent e) {
                        if (e.getClickCount() == 1) {
                            popup.setVisible(true);
                            System.out.println("Clicked");
                        }
                    }
                });
     
                popup.addFocusListener(new FocusAdapter() {
                    public void focusLost(FocusEvent evt) {
                        System.out.println("focusLost");
     
                            popup.setVisible(false);
     
     
                    }
                });
    Last edited by cnmeysam; April 4th, 2021 at 11:45 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    You may have to took at the how focus works.
    An interesting discussion here: https://stackoverflow.com/questions/...er-not-working
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3

    Default Re: close JPopupMenu after focus lost

    it is from jbutton and don't work for me

    popup.addFocusListener(new FocusListener() {
            @Override
            public void focusLost(FocusEvent e) {
                System.out.println("LOST FOCUS");
                popup.setVisible(false);
            }
     
            @Override
            public void focusGained(FocusEvent e) {
                System.out.println("GAINED FOCUS");
                popup.setVisible(true);
            }
        });

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    If you don't understand my answer, don't ignore it, ask a question.

  5. #5

    Default Re: close JPopupMenu after focus lost

    As I have noticed, the JPopupMenu does not focus at all after opening,
    i use
    popup.setFocusable(true); 
    popup.grabFocus();
    and
     popup.addFocusListener(new FocusListener() {
     @Override
     public void focusLost(FocusEvent e) {
      System.out.println("LOST FOCUS");
    popup.setVisible(false);
     }
     
     @Override
     public void focusGained(FocusEvent e) {
      System.out.println("GAINED FOCUS");
     }
    });
    but don't work
    so I can not run focus lost on it.
    This problem occurs in the following code
    https://www.javaprogrammingforums.co...tml#post171201
    Do you have a solution for that?
    Last edited by cnmeysam; April 1st, 2021 at 01:07 PM.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    I noticed the same thing: popup menus do not get the focus.

    Another solution make be to always hide the popup after any item is selected.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7

    Unhappy Re: close JPopupMenu after focus lost

    I have no problem hiding pop-ups after clicking on menus
    My problem is when I want to click outside the pop-up, that is, when I click on the desktop, the pop-up closes or hide
    Even if you can set the focus on the menus to close the popup after losing focus, it solves the problem, but I tested it nicely but it did not work.

             Info.setFocusable(true);
                        Info.grabFocus();
     
     
    Info.addFocusListener(new FocusListener() {
                    @Override
                    public void focusLost(FocusEvent e) {
                        System.out.println("LOST FOCUS");
                        Info.setBackground(Color.BLUE);
                    }
     
                    @Override
                    public void focusGained(FocusEvent e) {
                        System.out.println("GAINED FOCUS");
                        Info.setBackground(Color.RED);
                    }
                });
    It does not give an error message, but it does not work

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    I want to click outside the pop-up
    But that is not detectable by the program; so then it needs to require a user click on a menu item.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9

    Default Re: close JPopupMenu after focus lost

    I think the place where I put the code snippet may be wrong
    Since other programs do not have this problem, can we say that this is a bug in Java?
    and i use JMenuItem and JPopupMenu not menuitem and popupMenu in the form JMenuItem and JPopupMenu focusable and focus works in them
    Last edited by cnmeysam; April 1st, 2021 at 01:32 PM.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    Since you have written your own code for displaying the popup, you need to find a way to get focus or to detect when a click is outside the menuitems.

    If you use the old AWT code: trayIcon.setPopupMenu(popup); then the popup is cleared when a click is made away from the menu.
    But you need the new Swing components to get the right alignment of the text inside the items.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11

    Lightbulb Re: close JPopupMenu after focus lost

    Pointer is used in the codes
    Is it possible to make a new pointer and compare these two pointers?
    If so how?
    something like this
    Point point1 = new Point(500, 500);
                if (point1 != popup.getLocation()) {
                    popup.setVisible(false);
                    System.out.println("popup.setVisible(false)");
                }

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    Pointer is used in the codes
    What is Pointer? Where is it used?

    Can you use the AWT versions of the components and set the Font to be RTL?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13

    Default Re: close JPopupMenu after focus lost

    i use pointer like this for popup location
     
            Info.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Info.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Info.setBackground(UIManager.getColor("control"));
                }
            });
            Exit.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(Color.RED);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(UIManager.getColor("control"));
                }
            });
     
            Open.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Open.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Open.setBackground(UIManager.getColor("control"));
                }
            });
    Can you use the AWT versions of the components and set the Font to be RTL? yes i can but i cant find java system tray popup set right to left
    Last edited by cnmeysam; April 3rd, 2021 at 06:58 PM.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    java system tray popup set right to left
    What is that? Before you were asking about the text inside of the menuitems.
    What are you wanting to now? What things are supposed to be right to left?


    i use pointer
    Sorry, I do not see anything called pointer in that code.
    I see a Point object is that what you are talking about?
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    cnmeysam (April 1st, 2021)

  16. #15

    Default Re: close JPopupMenu after focus lost

    sorry it's my fault
    Point object is that what i talking about
    To align the menus, I have aligned both the pop-ups and the menus right to left
    I want the menus inside the pop-up to be right to left, to have icons behind the menus, to display the menus when I clicked on the system Icon, and to close the pop-up if I clicked on the desktop outside the pop-up.
    In the code I wrote, all this is done, but when I click on the desktop, the pop-up does not close.
    When searching on Google, the only issue related to my problem for pop-up alignment is just this link
    https://www.javaprogrammingforums.co...tml#post171201
    i search in Persian language Arabic language and English
    Last edited by cnmeysam; April 1st, 2021 at 04:56 PM.

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    The problem with the code at that link is that it is just bits and pieces. It is not code that can be copied, compiled and executed for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17

    Default Re: close JPopupMenu after focus lost

    i think this works for test You just have to replace the path and name of your photos and fonts name in this code
     
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import static java.awt.Frame.ICONIFIED;
    import static java.awt.Frame.MAXIMIZED_BOTH;
    import static java.awt.Frame.NORMAL;
    import java.awt.GraphicsConfiguration;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.SystemTray;
    import java.awt.Toolkit;
    import java.awt.TrayIcon;
    import java.awt.TrayIcon.MessageType;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.UIManager;
     
    public class NewClass extends javax.swing.JFrame {
     
     
        public NewClass() {
            initComponents();
            //systemtray();
        }
     
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addWindowStateListener(new java.awt.event.WindowStateListener() {
                public void windowStateChanged(java.awt.event.WindowEvent evt) {
                    formWindowStateChanged(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
     
            pack();
        }// </editor-fold>                        
     
        private void formWindowStateChanged(java.awt.event.WindowEvent evt) {                                        
     
            if (evt.getNewState() == ICONIFIED) {
                //System.out.println("unable to add to tray");
     
                systemtray();
                setVisible(false);
            }
            if (evt.getNewState() == 7) {
                //System.out.println("unable to add to system tray");
     
                systemtray();
                setVisible(false);
            }
            if (evt.getNewState() == MAXIMIZED_BOTH) {
                SystemTray.getSystemTray().remove(ti);
                popup.removeAll();
                popup.setVisible(false);
                setVisible(true);
                //System.out.println("Tray icon removed");
            }
            if (evt.getNewState() == NORMAL) {
                SystemTray.getSystemTray().remove(ti);
                popup.removeAll();
                popup.setVisible(false);
                setVisible(true);
                //System.out.println("Tray icon removed");
            }
        }                                       
    final JPopupMenu popup = new JPopupMenu();
        TrayIcon ti;
     
        public void systemtray() {
     
            try {
                ti = new TrayIcon(ImageIO.read(getClass().getResource("/images/kabe.jpg")), "Have a nice day");
     
                JMenuItem Exit = new JMenuItem("خروج");
                Exit.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
                Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit.png"))); // NOI18N
                JMenuItem Open = new JMenuItem("نمایش");
                Open.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
                Open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/kabe.jpg"))); // NOI18N
                JMenuItem Info = new JMenuItem("درباره ما");
                Info.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
                Info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/info.png"))); // NOI18N
     
    Info.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseEntered(java.awt.event.MouseEvent evt) {
                        Info.setBackground(Color.GREEN);
                    }
     
                    public void mouseExited(java.awt.event.MouseEvent evt) {
                        Info.setBackground(UIManager.getColor("control"));
                    }
                });
                Exit.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseEntered(java.awt.event.MouseEvent evt) {
                        Exit.setBackground(Color.GREEN);
                    }
     
                    public void mouseExited(java.awt.event.MouseEvent evt) {
                        Exit.setBackground(UIManager.getColor("control"));
                    }
                });
     
                Open.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseEntered(java.awt.event.MouseEvent evt) {
                        Open.setBackground(Color.GREEN);
                    }
     
                    public void mouseExited(java.awt.event.MouseEvent evt) {
                        Open.setBackground(UIManager.getColor("control"));
                    }
                });
     
     
     
                Exit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        SystemTray.getSystemTray().remove(ti);
                        System.exit(0);
                    }
                });
     
                Open.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JFrame frame = new JFrame();
                        frame.setVisible(true);
    //                    setExtendedState(JFrame.NORMAL);
                        ti.displayMessage("Open form", "Frame is opened", MessageType.NONE);
                          popup.removeAll();
                          popup.setVisible(false);
                          setExtendedState(JFrame.NORMAL);
     
                    }
                });
     
                Info.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JFrame frameinfo = new JFrame();
                        frameinfo.setVisible(true);
    //                    setExtendedState(JFrame.NORMAL);
                    }
                });
     
                popup.add(Open);
                popup.addSeparator();
                popup.add(Info);
                popup.addSeparator();
                popup.add(Exit);
     
    //            popup.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
                popup.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
                popup.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
     
                Open.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        setVisible(true);
                        setExtendedState(JFrame.NORMAL);
                    }
                });
     
                Exit.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.exit(0);
                    }
                });
     
                ti.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
                            Rectangle bounds = getSafeScreenBounds(e.getPoint());
                            Point point = e.getPoint();
                            int x = point.x;
                            int y = point.y;
                            if (y < bounds.y) {
                                y = bounds.y;
                            } else if (y > bounds.y + bounds.height) {
                                y = bounds.y + bounds.height;
                            }
                            if (x < bounds.x) {
                                x = bounds.x;
                            } else if (x > bounds.x + bounds.width) {
                                x = bounds.x + bounds.width;
                            }
                            if (x + popup.getPreferredSize().width > bounds.x + bounds.width) {
                                x = (bounds.x + bounds.width) - popup.getPreferredSize().width;
                            }
                            if (y + popup.getPreferredSize().height > bounds.y + bounds.height) {
                                y = (bounds.y + bounds.height) - popup.getPreferredSize().height;
                            }
                            popup.setLocation(x, y);
                           if (popup.isVisible()) {
                            popup.setVisible(false);
                            System.out.println("isVisible");
                        }
                            else{
                                popup.setVisible(true);
                            }
                        }
                    }
                });
                SystemTray.getSystemTray().add(ti);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
        public static Rectangle getSafeScreenBounds(Point pos) {
     
            Rectangle bounds = getScreenBoundsAt(pos);
            Insets insets = getScreenInsetsAt(pos);
     
            bounds.x += insets.left;
            bounds.y += insets.top;
            bounds.width -= (insets.left + insets.right);
            bounds.height -= (insets.top + insets.bottom);
     
            return bounds;
     
        }
     
        public static Insets getScreenInsetsAt(Point pos) {
            GraphicsDevice gd = getGraphicsDeviceAt(pos);
            Insets insets = null;
            if (gd != null) {
                insets = Toolkit.getDefaultToolkit().getScreenInsets(gd.getDefaultConfiguration());
            }
            return insets;
        }
     
        public static Rectangle getScreenBoundsAt(Point pos) {
            GraphicsDevice gd = getGraphicsDeviceAt(pos);
            Rectangle bounds = null;
            if (gd != null) {
                bounds = gd.getDefaultConfiguration().getBounds();
            }
            return bounds;
        }
     
        public static GraphicsDevice getGraphicsDeviceAt(Point pos) {
     
            GraphicsDevice device = null;
     
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice lstGDs[] = ge.getScreenDevices();
     
            ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);
     
            for (GraphicsDevice gd : lstGDs) {
     
                GraphicsConfiguration gc = gd.getDefaultConfiguration();
                Rectangle screenBounds = gc.getBounds();
     
                if (screenBounds.contains(pos)) {
     
                    lstDevices.add(gd);
     
                }
     
            }
     
            if (lstDevices.size() > 0) {
                device = lstDevices.get(0);
            } else {
                device = ge.getDefaultScreenDevice();
            }
     
            return device;
     
        }
     
        public static void main(String args[]) {
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewClass().setVisible(true);
                }
            });
        }
     
     
    }
    Last edited by cnmeysam; April 1st, 2021 at 06:52 PM.

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    Maybe instead of a popup to show the menu, use a dialog.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19

    Default Re: close JPopupMenu after focus lost

    Can you write me a sample inside my code?

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    Sorry. I think it would be a lot of work and I do not have the time right now.

    Try asking your question on this forum: https://coderanch.com/forums

    Continued here: https://coderanch.com/t/740977/java/...enu-focus-lost
    If you don't understand my answer, don't ignore it, ask a question.

  22. The Following User Says Thank You to Norm For This Useful Post:

    cnmeysam (April 1st, 2021)

  23. #21

    Default Re: close JPopupMenu after focus lost

    thanks
    Last edited by cnmeysam; April 1st, 2021 at 09:33 PM.

  24. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,110
    Thanks
    65
    Thanked 2,717 Times in 2,667 Posts

    Default Re: close JPopupMenu after focus lost

    Here's an attempt. I copied a lot of your code:
    /*
    Creates a small, transparent window in upper left of screen (60,20) for testing
    Creates a TrayIcon with a MouseListener
    When the TI is clicked, creates a transparent window and positions a popup window over it.
    The popup window is cleared with focus for the window is lost.
     
    Note:  Has lots of extra code left over from testing and hunting for a solution
    */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.imageio.ImageIO;
     
    public class WindowTest {
     
     
       //---------------------------------------------------------------
       public static void main(String[] args) {
          JPopupMenu popup = new JPopupMenu();
          WindowTest wt = new WindowTest(popup, 60,20);
          wt.loadPopup(popup);
          wt.setTI();
       }
     
       //---------------------------------------------------------
       public WindowTest(JPopupMenu popup, int x, int y) {
    //      Window win = new Window(new Frame()); //null);
          JDialog win = new JDialog(new Frame()); //null);
          win.setUndecorated(true);
     
          JMenuBar mnBar = new JMenuBar();           //Works
          final JMenu men = new JMenu("Test");      //<< Shows Test and a Right caret
          JMenuItem mi1 = new JMenuItem("one");      //
          men.add(mi1);
          mnBar.add(men);
          win.setLayout(new BorderLayout());
    //      win.add(mnBar, BorderLayout.NORTH);
     
          win.setBounds(x,y,100, 100);
          win.setOpacity(0.05f);
    //      win.setBackground(
          win.setVisible(true);
     
          win.setFocusable(true);
    //      loadPopup(popup);
     
          win.addMouseListener(new MouseAdapter() {
              @Override
              public void mouseClicked(MouseEvent e) {
                 System.out.println("mC at "+e.getPoint());                     // WORKS
                 //  Place and show popup
                 popup.setLocation(e.getPoint());
                 popup.setVisible(true);
                 if(e.getPoint().y > 90)
                    System.exit(0);
              }
          });
     
     
          mnBar.addFocusListener(new FocusAdapter() {
              @Override
              public void focusLost(FocusEvent evt) {
                  System.out.println("focusLost");         //<<<< never 
                  popup.setVisible(false);
              }
              @Override
              public void focusGained(FocusEvent evt) {
                  System.out.println("focusGained");       //  ditto
              }
          });
          win.addWindowFocusListener(new WindowFocusListener()  {
              @Override
              public void windowLostFocus(WindowEvent evt) {
                  System.out.println("WfocusLost");         //<<<< THIS ONE 
                  popup.setVisible(false);           
              }
              @Override
              public void windowGainedFocus(WindowEvent evt) {
                  System.out.println("WfocusGained");       //  ditto
              }
          });
          win.requestFocus();                 // nothing
          men.requestFocusInWindow();         // nothing
     
          System.out.println("isFocusable()="+win.isFocusable()); // isFocusable()=true
     
       }
       //----------------------------------------------
       public void setTI() {
          try {
             TrayIcon ti = new TrayIcon(ImageIO.read(getClass().getResource("https://www.javaprogrammingforums.com/images/ColorBand.png")), "Have a nice day");
             ti.addMouseListener(new MouseAdapter() {
                 @Override
                 public void mouseClicked(MouseEvent e) {
                    System.out.println("mC for ti at "+e.getPoint());
                    //  What x,y for the popup????
                    int x = e.getPoint().x;
                    int y = e.getPoint().y;
     
                    // Create our own local popup to respond to TrayIcon click
                    JPopupMenu popup = new JPopupMenu();
                    new WindowTest(popup, x-20, y-20);
                    loadPopup(popup);
                    popup.setLocation(x-10, y-10);
                    popup.setVisible(true);
     
                 }
              });
              SystemTray.getSystemTray().add(ti);      //<<<<<<<
           }catch (Exception ex) {ex.printStackTrace();}
        }
     
       //--------------------------------------------------------------------------
       public void loadPopup(JPopupMenu popup) {
             JMenuItem Exit = new JMenuItem("Exit");
             Exit.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
             Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("https://www.javaprogrammingforums.com/images/RedCar.png"))); //exit.png"))); // NOI18N
             JMenuItem Open = new JMenuItem("Open it");
             Open.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
             Open.setIcon(new javax.swing.ImageIcon(getClass().getResource("https://www.javaprogrammingforums.com/images/GreenCar.png"))); //kabe.jpg"))); // NOI18N
             JMenuItem Info = new JMenuItem("Show info");
             Info.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
             Info.setIcon(new javax.swing.ImageIcon(getClass().getResource("https://www.javaprogrammingforums.com/images/BlueCar.png"))); //info.png"))); // NOI18N
     
             Exit.addActionListener(new ActionListener() {
                 @Override
                 public void actionPerformed(ActionEvent e) {
                     System.exit(0);
                 }
             });
     
             Open.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     JFrame frame = new JFrame();
                     frame.setVisible(true);
    //                    setExtendedState(JFrame.NORMAL);
    //                      popup.removeAll();
                     popup.setVisible(false);
    //                      setExtendedState(JFrame.NORMAL);
     
                 }
             });
     
             Info.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     JFrame frameinfo = new JFrame();
                     frameinfo.setVisible(true);
    //                    setExtendedState(JFrame.NORMAL);
                 }
             });
     
             popup.add(Open);
             popup.addSeparator();
             popup.add(Info);
             popup.addSeparator();
             popup.add(Exit);
     
    //            popup.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
             popup.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
             popup.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
     
       }  // end loadPopup
    }
    If you don't understand my answer, don't ignore it, ask a question.

  25. The Following User Says Thank You to Norm For This Useful Post:

    cnmeysam (April 2nd, 2021)

  26. #23

    Default Re: close JPopupMenu after focus lost

    thanks a lot its work correctly

  27. #24

    Red face Re: close JPopupMenu after focus lost

    I'm sorry to bother you when i add to your class in
    public void loadPopup(JPopupMenu popup)
    this codes for color menu items when mouse hover Entered or Exited It works properly
    Info.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Info.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Info.setBackground(UIManager.getColor("control"));
                }
            });
            Exit.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(Color.RED);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(UIManager.getColor("control"));
                }
            });
     
            Open.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Open.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Open.setBackground(UIManager.getColor("control"));
                }
            });
    but wen use this codes in gui frame colors not working These are my codes in gui frame
     
     
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.imageio.ImageIO;
     
    public class trayform extends javax.swing.JFrame {
     
        private static trayform obj = null;
     
        private trayform() {
            initComponents();
     
            JPopupMenu popup = new JPopupMenu();
            loadPopup(popup);
            setTI();
        }
     
        public static trayform getobj() {
            if (obj == null) {
                obj = new trayform();
            }
            return obj;
        }
     
        public trayform(JPopupMenu popup, int x, int y) {
    //      Window win = new Window(new Frame()); //null);
            JDialog win = new JDialog(new Frame()); //null);
            win.setUndecorated(true);
     
            JMenuBar mnBar = new JMenuBar();           //Works
            final JMenu men = new JMenu("Test");      //<< Shows Test and a Right caret
            JMenuItem mi1 = new JMenuItem("one");      //
            men.add(mi1);
            mnBar.add(men);
            win.setLayout(new BorderLayout());
    //      win.add(mnBar, BorderLayout.NORTH);
     
            win.setBounds(x, y, 100, 100);
            win.setOpacity(0.05f);
    //      win.setBackground(
            win.setVisible(true);
     
            win.setFocusable(true);
    //      loadPopup(popup);
     
            win.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("mC at " + e.getPoint());                     // WORKS
                    //  Place and show popup
                    popup.setLocation(e.getPoint());
                    popup.setVisible(true);
                    if (e.getPoint().y > 90) {
                        System.exit(0);
                    }
                }
            });
     
            mnBar.addFocusListener(new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent evt) {
                    System.out.println("focusLost");         //<<<< never 
                    popup.setVisible(false);
                }
     
                @Override
                public void focusGained(FocusEvent evt) {
                    System.out.println("focusGained");       //  ditto
                }
            });
            win.addWindowFocusListener(new WindowFocusListener() {
                @Override
                public void windowLostFocus(WindowEvent evt) {
                    System.out.println("WfocusLost");         //<<<< THIS ONE 
                    popup.setVisible(false);
                }
     
                @Override
                public void windowGainedFocus(WindowEvent evt) {
                    System.out.println("WfocusGained");       //  ditto
                }
            });
            win.requestFocus();                 // nothing
            men.requestFocusInWindow();         // nothing
     
            System.out.println("isFocusable()=" + win.isFocusable()); // isFocusable()=true
     
        }
     
        //----------------------------------------------
        TrayIcon ti;
     
        public void setTI() {
            try {
                ti = new TrayIcon(ImageIO.read(getClass().getResource("/images/kabe.jpg")), "Have a nice day");
                ti.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("mC for ti at " + e.getPoint());
                        //  What x,y for the popup????
                        int x = e.getPoint().x;
                        int y = e.getPoint().y;
     
                        // Create our own local popup to respond to TrayIcon click
                        JPopupMenu popup = new JPopupMenu();
                        new trayform(popup, x - 20, y - 20);
                        loadPopup(popup);
                        popup.setLocation(x - 12, y - 95);
                        popup.setVisible(true);
     
                    }
                });
                SystemTray.getSystemTray().add(ti);      //<<<<<<<
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
        //--------------------------------------------------------------------------
        public void loadPopup(JPopupMenu popup) {
            JMenuItem Exit = new JMenuItem("خروج");
            Exit.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
            Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit.png"))); //exit.png"))); // NOI18N
            JMenuItem Open = new JMenuItem("نمایش");
            Open.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
            Open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/kabe.jpg"))); //kabe.jpg"))); // NOI18N
            JMenuItem Info = new JMenuItem("درباره ما");
            Info.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
            Info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/info.png"))); //info.png"))); // NOI18N
     
            Info.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Info.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Info.setBackground(UIManager.getColor("control"));
                }
            });
            Exit.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(Color.RED);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Exit.setBackground(UIManager.getColor("control"));
                }
            });
     
            Open.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    Open.setBackground(Color.GREEN);
                }
     
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    Open.setBackground(UIManager.getColor("control"));
                }
            });
     
            Exit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
     
            Open.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
    //                JFrame frame = new JFrame();
    //                frame.
                    setVisible(true);
                    popup.setVisible(false);
    //                frame.
                    setExtendedState(JFrame.NORMAL);
     
                }
            });
     
            Info.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ti.displayMessage("Open form", "Frame is opened", TrayIcon.MessageType.NONE);
                }
            });
     
            popup.add(Open);
            popup.addSeparator();
            popup.add(Info);
            popup.addSeparator();
            popup.add(Exit);
     
    //            popup.setComponentOrientation(ComponentOrientation  .RIGHT_TO_LEFT);
            popup.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            popup.setFont(new java.awt.Font("B Nazanin", 1, 18)); // NOI18N
     
        }  // end loadPopup
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addWindowStateListener(new java.awt.event.WindowStateListener() {
                public void windowStateChanged(java.awt.event.WindowEvent evt) {
                    formWindowStateChanged(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
     
            setSize(new java.awt.Dimension(416, 339));
            setLocationRelativeTo(null);
        }// </editor-fold>                        
     
        private void formWindowStateChanged(java.awt.event.WindowEvent evt) {                                        
            // TODO add your handling code here:
            if (evt.getNewState() == ICONIFIED) {
                //System.out.println("unable to add to tray");
                setVisible(false);
            }
            if (evt.getNewState() == 7) {
                //System.out.println("unable to add to system tray");
     
                setVisible(false);
            }
            if (evt.getNewState() == MAXIMIZED_BOTH) {
     
                setVisible(true);
                //System.out.println("Tray icon removed");
            }
            if (evt.getNewState() == NORMAL) {
     
                setVisible(true);
                //System.out.println("Tray icon removed");
            }
        }                                       
     
        public static void main(String args[]) {
     
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(trayform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(trayform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(trayform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(trayform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
     
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new trayform().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify                     
        // End of variables declaration                   
    }

    how i must fix it?
    Last edited by cnmeysam; April 3rd, 2021 at 02:37 AM.

  28. #25

    Default Re: close JPopupMenu after focus lost

    pleas pleas pleas help meeeee

Page 1 of 2 12 LastLast

Similar Threads

  1. how can i set an object in focus
    By ankushpruthi in forum What's Wrong With My Code?
    Replies: 10
    Last Post: October 1st, 2013, 07:01 AM
  2. Replies: 1
    Last Post: June 20th, 2013, 01:45 PM
  3. Focus is in the wrong spot
    By walker6o9 in forum AWT / Java Swing
    Replies: 0
    Last Post: January 15th, 2013, 11:51 PM
  4. [SOLVED] KeyListeners Require Focus...
    By snowguy13 in forum AWT / Java Swing
    Replies: 2
    Last Post: January 6th, 2012, 08:15 AM
  5. KeyListeners: Automatic Focus?
    By bgroenks96 in forum Java Theory & Questions
    Replies: 32
    Last Post: June 24th, 2011, 09:03 PM

Tags for this Thread