Java 怎么设置Swing组件(Component)尺寸

2019年8月18日22:02:38 评论 23

1.简介

Java 怎么设置Swing组件(Component)尺寸?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import javax.swing.*;
import java.awt.*;

public class Main{
    public static void setDimension(final Component component,
            final String text) {
        setDimension(component, getDimension(component, text));
    }
    public static void setDimension(Component component, Dimension dimension) {
        component.setSize(dimension);
        component.setPreferredSize(dimension);
        component.setMaximumSize(dimension);
        component.setMinimumSize(dimension);
    }
    public static Dimension getDimension(final Component component,
            String text) {

        FontMetrics fm = component.getFontMetrics(component.getFont());
        if (text == null) {
            text = "";
        }
        if (component instanceof PDBButton) {
            Icon icon = ((PDBButton) component).getIcon();
            int iconWidth = icon == null ? 0 : icon.getIconWidth();
            return new Dimension(fm.stringWidth(text) + 40 + iconWidth,
                    Math.max(20, fm.getHeight()));
        } else if (component instanceof PDBCheckBox) {
            return new Dimension(fm.stringWidth(text) + 40, 20);
        } else {
            return new Dimension(fm.stringWidth(text), fm.getHeight());
        }

    }
    public static Dimension getDimension(final Component component,
            final String text, final int x, final int y) {
        FontMetrics fm = component.getFontMetrics(component.getFont());
        return new Dimension(fm.stringWidth(text) + x, fm.getHeight() + y);
    }
}

 

3.总结

示例代码演示了 Java 怎么设置Swing组件(Component)尺寸,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: