- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to display a JFrame to the center of a screen in Java?
A JFrame is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. We can add the components to a JFrame to use its contentPane instead. A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame.
By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.
Syntax
public void setLocationRelativeTo(Component c)
Example
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(); } }
Output
- Related Articles
- How to center a window on the screen in Tkinter?
- How to center a div on the screen using jQuery?
- How to close JFrame on the click of a Button in Java
- How to set location of JLabel in a JFrame with Java?
- How to center a popup window on screen using JavaScript?
- How to display a button in random screen position?
- How to disable close button on a JFrame in Java?
- How to create a Titleless and Borderless JFrame in Java?
- How to center a Window in Java?
- Java Program to draw a line on a JFrame in Java
- How to maximize JFrame in Java Swing
- Align HTML5 SVG to the center of the screen
- How to Align the modal content box to the center of any screen?
- How to set minimum size limit for a JFrame in Java
- How to center align the items of a JComboBox in Java?

Advertisements