搜尋
首頁Javajava教程如何在Java中將JFrame準確地居中在螢幕上?

How to Accurately Center a JFrame on the Screen in Java?

了解JFrame 尺寸並確定精確中心

在Java 中,使用JFrame 時,了解框架整體尺寸之間的差異至關重要以及內容窗格中的可繪製區域。

JFrame 由多個組件組成,包括框架、JRootPane 和 JLayeredPane。內容窗格駐留在 JLayeredPane 內。需要注意的是,框架的尺寸包括邊框,而可繪製區域則不包括。

因此,要準確計算確切的中間位置,您需要考慮內容窗格的尺寸而不是框架的整體尺寸。內容窗格的中心點可以使用這些調整後的尺寸來確定。

例如,如果您建立預設大小為 200x200 像素的 JFrame,則內容窗格的中心點將為 92x81 像素(假設邊框寬度為 8 像素)。

要將 JFrame 在螢幕上置中,可以使用 setLocationRelativeTo(null) 方法。但是,如果您想動態確定螢幕的確切中心,無論其當前大小如何,您可以採用以下解決方案:

import java.awt.*;

public class ScreenCenter {

    public static Point getScreenCenter(Component component) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension componentSize = component.getSize();

        int x = (screenSize.width - componentSize.width) / 2;
        int y = (screenSize.height - componentSize.height) / 2;

        return new Point(x, y);
    }

    public static void main(String[] args) {
        // Create a JFrame and set its size
        JFrame frame = new JFrame("Frame");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Center the JFrame on the screen using the getScreenCenter method
        Point centerPoint = getScreenCenter(frame);
        frame.setLocation(centerPoint.x, centerPoint.y);

        // Display the JFrame
        frame.setVisible(true);
    }
}

此程式碼會自動調整JFrame 的位置以根據當前螢幕尺寸,確保一致的使用者體驗。

以上是如何在Java中將JFrame準確地居中在螢幕上?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器