Home Tutorial Java Swing How to center a frame

 
 

Share on Google+Share on Google+
How to center a frame
Posted on: September 25, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to center a frame on screen.

How to center a frame

In this tutorial, you will learn how to center a frame on screen.

A Frame is a top-level window having a title and a border and its size includes any area designates for the border. You can resize, move, maximize and minimize also. Here we are going to center the frame on the screen. The best way to do this is to use the java.awt.Toolkit api. The given code center the window on the desktop regardless of the resolution of the screen:

Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);

Example:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class AboutDialog extends JFrame {
  public AboutDialog() {
    setTitle("CenteredFrame");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();
    int screenHeight = screenSize.height;
    int screenWidth = screenSize.width;
    setSize(screenWidth / 2, screenHeight / 2);
    setLocation(screenWidth / 4, screenHeight / 4);
  }

  public static void main(String[] args) {
    JFrame frame = new AboutDialog();
	frame.add(new JLabel("Welcome To Roseindia Technologies"));
    frame.show();
  }
}
Advertisement

Related Tags for How to center a frame:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 25, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com