How to center a Window in Java?

Java 8Object Oriented ProgrammingProgramming

To center a Window in Java, use the getCenterPoint() method. Set the width and height and use the below formulae to set bounds −

Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
int width = 500;
int height = 200;
frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);

The following is an example to center a window −

Example

package my;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame.setDefaultLookAndFeelDecorated(true);
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField age = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(age);
      frame.add(passwd);
      Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
      int width = 500;
      int height = 200;
      frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);
      frame.setVisible(true);
   }
}

The output is as follows. The Window will appear in the center of the screen −

Output

raja
Published on 03-Jun-2019 12:06:36
Advertisements