fit Popup Menu Inside Screen - Java Swing

Java examples for Swing:Screen

Description

fit Popup Menu Inside Screen

Demo Code

// Copyright (c) 1996 - 1999, 2003 by Yoshiki Shibata. All rights reserved.
//package com.java2s;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;

import java.awt.Toolkit;

public class Main {
    private static Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit()
            .getScreenSize();/*from  w  w w .  j a va2s  .  c  o  m*/
    private static final int WINDOWS_BAR_HEIGHT_OFFSET = 32;

    static public Point fitPopupMenuInsideScreen(Component parentComponent,
            Component popupMenu, Point relativeLocation) {
        Point parentLocation = parentComponent.getLocationOnScreen();
        Dimension preferredSize = popupMenu.getPreferredSize();
        preferredSize.height += WINDOWS_BAR_HEIGHT_OFFSET;
        Point absoluteLocation = new Point(parentLocation.x
                + relativeLocation.x, parentLocation.y + relativeLocation.y);
        Point newAbsoluteLocation = fitComponentInsideScreen(preferredSize,
                absoluteLocation);

        return (new Point(newAbsoluteLocation.x - parentLocation.x,
                newAbsoluteLocation.y - parentLocation.y));
    }

    static public Point fitComponentInsideScreen(Dimension componentSize,
            Point location) {
        Point newLocation = new Point(location.x, location.y);

        if (newLocation.x < 0)
            newLocation.x = 0;
        if (newLocation.y < 0)
            newLocation.y = 0;

        if ((newLocation.x + componentSize.width) > SCREEN_SIZE.width)
            newLocation.x = SCREEN_SIZE.width - componentSize.width;
        if ((newLocation.y + componentSize.height) > SCREEN_SIZE.height)
            newLocation.y = SCREEN_SIZE.height - componentSize.height;

        return (newLocation);
    }

    static public Point fitComponentInsideScreen(Component component,
            Point location) {
        return (fitComponentInsideScreen(component.getSize(), location));
    }
}

Related Tutorials