Qué hacer si el menú contextual se sale de la pantalla

1953 vistas

JDK 1.3 y anteriores:
Cuando usamos el método show(java.awt.Component, int, int) para mostrar un javax.swing.JPopupMenu, las coordenadas de "inicio de despliegue" del menú corresponden a la esquina superior izquierda. Si estas coordenadas están demasiado cercas del borde de la pantalla, veremos que parte del menú no se visualiza. Para poder arreglar el problema, tenemos que sobrecargar el método show() y corregir las coordenadas si estamos cerca del borde de la pantalla.



java
  1. class MiPopupMenu extends JPopupMenu {
  2.         public void show(Component invoker, int x, int y) {
  3.                 /** Dimension de la pantalla */
  4.                 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  5.                 /** Dimension del Menu popup */
  6.                 Dimension popupSize = this.getPreferredSize();
  7.                 /** Posición x,y del popup en pantalla */
  8.                 double xPopupDisplay = invoker.getLocationOnScreen().getX() + x;
  9.                 double yPopupDisplay = invoker.getLocationOnScreen().getY() + y;
  10.                 /** si el popup se sale de la pantalla por la derecha, decrementamos la x */
  11.                 if ((xPopupDisplay + popupSize.getWidth()) > screenSize.getWidth()) {
  12.                         x = x - (int)popupSize.getWidth();
  13.                 }
  14.                 /** si el popup se sale por debajo, decrementamos la y */
  15.                 if ((yPopupDisplay + popupSize.getHeight()) > screenSize.getHeight()) {
  16.                         y = y - (int)popupSize.getHeight();
  17.                 }
  18.                 /** mostramos el popup */
  19.                 super.show(invoker, x, y);
  20.         }
  21. }



JDK 1.4:
Este bug ya ha sido corregido y no hace falta realizar nada.