欢迎访问宙启技术站
智能推送

如何在Java中实现窗体居中显示?

发布时间:2023-06-19 19:22:33

在Java语言中,窗体居中显示是一个常见的需求,可以通过以下方式实现。

种方法:使用工具包

Java语言提供了一些工具包可以实现窗体居中显示。其中,最常用的是AWT工具包和Swing工具包。使用AWT工具包时,需要通过对话框将窗体居中显示。以下是实现代码:

import java.awt.*;

public class CenterFrame extends Frame {

    public CenterFrame() {
        //设置窗体标题
        setTitle("居中显示窗体");

        //获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        //获取窗体尺寸
        int frameWidth = 400;
        int frameHeight = 300;

        //设置窗体左上角位置,使其居中显示
        setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);

        //设置窗体大小
        setSize(frameWidth, frameHeight);

        //设置窗体可见
        setVisible(true);
    }

    public static void main(String[] args) {
        new CenterFrame();
    }
}

使用Swing工具包时,同样需要通过对话框将窗体居中显示。以下是实现代码:

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

public class CenterFrame extends JFrame {

    public CenterFrame() {
        //设置窗体标题
        setTitle("居中显示窗体");

        //获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        //获取窗体尺寸
        int frameWidth = 400;
        int frameHeight = 300;

        //设置窗体左上角位置,使其居中显示
        setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);

        //设置窗体大小
        setSize(frameWidth, frameHeight);

        //设置窗体可见
        setVisible(true);
    }

    public static void main(String[] args) {
        new CenterFrame();
    }
}

第二种方法:使用窗体逻辑坐标

Java语言中还可以通过窗体逻辑坐标来实现窗体居中显示。以下是实现代码:

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

public class CenterFrame extends JFrame {

    public CenterFrame() {
        //设置窗体标题
        setTitle("居中显示窗体");

        //获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        //获取窗体尺寸
        int frameWidth = 400;
        int frameHeight = 300;

        //设置窗体左上角位置,使其居中显示
        setLocationRelativeTo(null);

        //设置窗体大小
        setSize(frameWidth, frameHeight);

        //设置窗体可见
        setVisible(true);
    }

    public static void main(String[] args) {
        new CenterFrame();
    }
}

使用窗体逻辑坐标时,只需将窗体位置设置为null即可。这种方法更加简洁。

总结

本文介绍了Java语言中实现窗体居中显示的两种方法。 种方法是使用工具包的对话框,通过计算窗体左上角的位置将其居中显示。 第二种方法是使用窗体逻辑坐标,将窗体位置设置为null即可实现窗体居中显示。 无论是哪种方法,都能够实现窗体居中显示的效果。