How to center a frame


 

How to center a frame

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

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();
  }
}

Ads