awt
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
TextAreaand a newButton. - Call
Toolkit.getDefaultToolkit().getScreenSize()to get the dimensions of the screen. - Use
(dim.width-width)/2and(dim.height-height)/2to set up the correct coordinates. - Call
Frame.setLocationto 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
frame.setVisible(true);
}
}
This was an example on how to center a frame on screen.

