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的配置、監控與優化,比較實用,值得學習。java

相關文章
相關標籤/搜索