user1486147
user1486147

Reputation:

How can I determine the midpoint of the users display?

I've written a Swing application. I want to set the JFrame to be centred in the user's screen. I can set it to the approximate center of my screen using:

JFrame frame = new JFrame("Test Frame");
Rectangle r = new Rectangle(600, 300, 400, 400);
frame.setBounds(r);

Is there a way to define the Rectangle r such that the center of it is at the center of any screen?

Is setBounds() the wrong method for varying the frame position dynamically?

Upvotes: 3

Views: 485

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Do you want to center a JFrame in the screen? If so then simply call setLocationRelativeTo(null) on the JFrame after calling pack(). You really don't want to set the size of the JFrame if you can avoid it, but instead have your layout managers do the size setting for you. The pack() method will ask the containers' layout managers to lay out their components and set the best sizes for their components.

Edit
Regarding your question:

Thanks, that's great. Any chance you could tell me where I could find the method details within docs.oracle

Since this method can be called on a JFrame, simply go to the JFrame API. If this is a method of a parent class, the API will tell you and provide the link to the parent class and its method.

Upvotes: 4

Related Questions