Ignora collegamentiHome / Blog

Blog


How to display a JFrame at the center of the screen with Java

Sometimes you need to display a JFrame at the center of the screen, this example demonstrates how to position a JFrame at the center of the screen:

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

public class GUITest
{
	private static int wJFrame = 400;	// JFrame width
	private static int hJFrame = 200;	// JFrame height
	
	private static int wScreen;	// Width of the Screen
	private static int hScreen;	// Height of the Screen
	
	public static void main(String[] args)
	{
	// Create the frame
	JFrame jframeTest = new JFrame();
	
	// Set the title of the frame
	jframeTest.setTitle("GUITest");
	
	// Set the size of the frame (widht, height)
	jframeTest.setSize(wJFrame, hJFrame);
	
	Dimension d = jframeTest.getToolkit().getScreenSize();
	wScreen = d.width;
	hScreen = d.height;
		
	// Set the location of the frame (x,y)	
	jframeTest.setLocation((wScreen-wJFrame)/2, (hScreen-hJFrame)/2);	
	jframeTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	jframeTest.setVisible(true);
	}
}

 



Category: Java