如何在 Java 中将 JFrame 显示在屏幕中央?
JFrame 是Frame 类的子类,添加到框架中的组件称为其内容,这些内容由contentPane管理。我们可以将组件添加到 JFrame,以代替使用它的contentPane 。JFrame就像一个带边框、标题和按钮的Window 。我们可以使用JFrame实现大多数 java swing 应用程序。
默认情况下,JFrame 可以显示在屏幕的左上角。我们可以使用Window 类的 setLocationRelativeTo() 方法显示 JFrame 的中心位置。
语法
public void setLocationRelativeTo(Component c)
示例
import javax.swing.*;
import java.awt.*;
public class JFrameCenterPositionTest extends JFrame {
public JFrameCenterPositionTest() {
setTitle("JFrameCenter Position");
add(new JLabel("JFrame set to center of the screen", SwingConstants.CENTER), BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // this method display the JFrame to center position of a screen
setVisible(true);
}
public static void main (String[] args) {
new JFrameCenterPositionTest();
}
}输出
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP