Fixes the size of a JComponent to the given width and height. - Java Swing

Java examples for Swing:JComponent

Description

Fixes the size of a JComponent to the given width and height.

Demo Code

/* Copyright (c) 2011 Danish Maritime Authority.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License./*from ww  w  .j  a va 2s  . co m*/
 */
//package com.java2s;

import java.awt.Dimension;

import javax.swing.JComponent;

public class Main {
    /**
     * Fixes the size of a {@linkplain JComponent} to the given width and height.
     * <p>
     * If a value of -1 is passed along, the preferred size is used instead.
     * 
     * @param comp the component to fix the size of
     * @param width the fixed width
     * @param height the fixed height
     * @return the updated component
     */
    public static <T extends JComponent> T fixSize(T comp, int width,
            int height) {
        // Sanity check
        if (comp == null) {
            return null;
        }

        if (width == -1) {
            width = (int) comp.getPreferredSize().getWidth();
        }
        if (height == -1) {
            height = (int) comp.getPreferredSize().getHeight();
        }
        Dimension dim = new Dimension(width, height);
        comp.setPreferredSize(dim);
        comp.setMaximumSize(dim);
        comp.setMinimumSize(dim);
        comp.setSize(dim);
        return comp;
    }

    /**
     * Fixes the size of a {@linkplain JComponent} to the given width
     * <p>
     * If a value of -1 is passed along, the preferred size is used instead.
     * 
     * @param comp the component to fix the size of
     * @param width the fixed width
     * @return the updated component
     */
    public static <T extends JComponent> T fixSize(T comp, int width) {
        return fixSize(comp, width, -1);
    }
}

Related Tutorials