📜  屏幕中间的Jframe java(1)

📅  最后修改于: 2023-12-03 14:53:57.189000             🧑  作者: Mango

屏幕中间的JFrame Java

在Java GUI编程中,JFrame是一个顶层容器,用于创建GUI界面。默认情况下,JFrame会在屏幕中心显示,但是当我们使用更复杂的布局时,它可能会被覆盖或者不再中心,这时我们需要将JFrame重新定位到屏幕中心。

代码实现
import javax.swing.*;
import java.awt.*;

public class CenteredJFrame extends JFrame {

    public CenteredJFrame() {
        initUI();
    }

    private void initUI() {
        setTitle("Centered JFrame");
        setSize(300, 200);
        setLocationRelativeTo(null); // 将JFrame重新定位到屏幕中心
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 点击窗口关闭按钮时退出程序
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            CenteredJFrame cf = new CenteredJFrame();
            cf.setVisible(true);
        });
    }
}
解析

代码中我们先创建了一个继承JFrame的类CenteredJFrame,并在构造函数中调用了initUI方法来初始化JFrame,设置窗口的标题和大小,并使用setLocationRelativeTo(null)将JFrame重新定位到屏幕中心。

在main方法中,我们使用了SwingUtilities的方法invokeLater来启动我们的JFrame。invokeLater方法用来保证我们的UI界面不会和其他线程抢占资源而出现混乱。

其他设置屏幕中心的方法

除了上面提到的setLocationRelativeTo(null),我们还可以通过以下两种方式来设置JFrame屏幕中心:

方法一:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = dim.width;
int screenHeight = dim.height;
int frameWidth = 300;
int frameHeight = 200;
setBounds((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, frameWidth, frameHeight);

方法二:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
GraphicsConfiguration gc = gd[0].getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
int screenWidth = bounds.width;
int screenHeight = bounds.height;
int frameWidth = 300;
int frameHeight = 200;
setLocation((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2);

这两种方法的本质都是为了获取屏幕的大小和JFrame的大小,从而确定它们在屏幕上的位置,使JFrame显示在屏幕中心。

总结

无论是使用哪种方式,将JFrame定位到屏幕中心这个小技巧都是GUI编程中经常使用的,既能显得整洁美观,同时又能提供最佳的用户体验。