fit Component Into Screen - Java Swing

Java examples for Swing:Screen

Description

fit Component Into 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 ww.  j  a v a  2s  . c  om*/

    static public void fitComponentIntoScreen(Component component,
            Point location) {
        Point newLocation = fitComponentInsideScreen(component, location);

        component.setLocation(newLocation);
    }

    static public void fitComponentIntoScreen(Component component) {
        fitComponentIntoScreen(component, component.getLocation());
    }

    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