Center Frame on screen example

In this example we are going to see how to center a Frame on the screen. This is very important when you have many windows opened to your application and you want to manage the important ones.

In short to center a Frame on screen, you have to follow these steps:

  • Create a new Frame.
  • Create a new TextArea and a new Button.
  • Call Toolkit.getDefaultToolkit().getScreenSize() to get the dimensions of the screen.
  • Use (dim.width-width)/2 and (dim.height-height)/2 to set up the correct coordinates.
  • Call Frame.setLocation to centralize the location to its new coordinates.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.Toolkit;

public class CenterFrame {

  public static void main(String[] args) {

// Create frame with specific title

Frame frame = new Frame("Example Frame");

// Create a component to add to the frame; in this case a text area with sample text

Component textArea = new TextArea("Sample text...");

// Create a component to add to the frame; in this case a button

Component button = new Button("Click Me!!");

// Add the components to the frame; by default, the frame has a border layout

frame.add(textArea, BorderLayout.NORTH);

frame.add(button, BorderLayout.SOUTH);

// Set frame size

int width = 300;

int height = 300;

frame.setSize(width, height);

// Get the size of the screen

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

// Determine the new location of the frame

int x = (dim.width-width)/2;

int y = (dim.height-height)/2;

// Move the frame

frame.setLocation(x, y);

// Show the frame



This was an example on how to center a frame on screen.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button