When I show a popup menu at the mouse cursor's position it often goes off screen when the cursor is near the right or bottom border.

Jan Borchers

This seems to be a little bug in Swing. The position of a popup menu is not 'auto-adjusted' by Swing.

You'll have to show the popup menu. Then check the menu's location against the screen's boundaries and move the menu if needed.

For example, suppose we have the following code in a MouseListener that invokes the popup:


public void mouseReleased(MouseEvent event)
{
  if(event.isPopupTrigger()){

    // show popup menu
    menu.show((Component)event.getSource(), 
              event.getX(), event.getY());

    // determine boundaries
    Point point = menu.getLocationOnScreen();
    Dimension size = menu.getSize();
    Rectangle oldRect = 
      new Rectangle(point.x, point.y, size.width, size.height);

    // helper function to move oldRect completely
    // onto screen (desktop) if necessary
    Rectangle newRect = ensureRectIsVisible(oldRect);

    // rects differ, need moving
    if(!oldRect.equals(newRect)){
      Window window = SwingUtilities.getWindowAncestor(menu);
      if(window != null){
        window.setLocation(newRect.x, newRect.y);
      }
    }
  }
}

// helper function to move a rectangle onto the screen
private Rectangle ensureRectIsVisible(Rectangle bounds)
{
  Dimension size = Toolkit.getDefaultToolkit().getScreenSize();

  return new Rectangle(Math.max(0, 
                                Math.min(size.width - bounds.width,
                                         bounds.x)),
                       Math.max(0, 
                                Math.min(size.height - bounds.height, 
                                         bounds.y)),
                       bounds.width,
                       bounds.height);
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact