Java基础 awt Frame 窗体在屏幕的中间显示

  •     JDK :OpenJDK-11
  •      OS :CentOS 7.6.1810
  •      IDE :Eclipse 2019‑03
  • typesetting :Markdown

code

package per.jizuiku.gui;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Toolkit;

/**
 * @author 给最苦
 * @date 2019/06/30
 * @blog www.cnblogs.com/jizuiku
 */
public class Demo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Frame f = new Frame();

        // 设置大小
        int width = 400;
        int height = 500;
        f.setSize(width, height);

        // 屏幕中间显示窗体
        center(f);

        // 可见
        f.setVisible(true);

    }

    /**
     * 
     * @param c
     */
    public static void center(Component c) {
        Toolkit kit = Toolkit.getDefaultToolkit();
        int x = (kit.getScreenSize().width - c.getWidth()) / 2;
        int y = (kit.getScreenSize().height - c.getHeight()) / 2;
        c.setLocation(x, y);
    }

}

sourceCode

/**
    * Gets the size of the screen.  On systems with multiple displays, the
    * primary display is used.  Multi-screen aware display dimensions are
    * available from {@code GraphicsConfiguration} and
    * {@code GraphicsDevice}.
    * @return    the size of this toolkit's screen, in pixels.
    * @exception HeadlessException if GraphicsEnvironment.isHeadless()
    * returns true
    * @see       java.awt.GraphicsConfiguration#getBounds
    * @see       java.awt.GraphicsDevice#getDisplayMode
    * @see       java.awt.GraphicsEnvironment#isHeadless
    */
public abstract Dimension getScreenSize()
    throws HeadlessException;
/**
    * Returns the current width of this component.
    * This method is preferable to writing
    * {@code component.getBounds().width},
    * or {@code component.getSize().width} because it
    * doesn't cause any heap allocations.
    *
    * @return the current width of this component
    * @since 1.2
    */
public int getWidth() {
    return width;
}

resource

  • [ JDK ] openjdk.java.net
  • [ doc - 参考 ] docs.oracle.com/en/java/javase/11
  • [ 规范 - 推荐 ] yq.aliyun.com/articles/69327
  • [ 规范 - 推荐 ] google.github.io/styleguide
  • [ 源码 ] hg.openjdk.java.net
  • [ OS ] www.centos.org
  • [ IDE ] www.eclipse.org/downloads/packages
  • [ 平台 ] www.cnblogs.com


感谢帮助过 给最苦 的人们。
Java、Groovy和Scala等基于JVM的语言,优秀,值得学习。
规范的命名和代码格式等,有助于沟通和理解。
JVM的配置、监控与优化,比较实用,值得学习。

posted @ 2019-06-30 16:13  给最苦  阅读(1046)  评论(0编辑  收藏  举报