I want my jframe to open in the center of a person's monitor.

(By default a jframe will open at coordinate. (0,0))

To achieve this, before setting the frame visible, I use this method.

this.setLocation(x,y);

In theory, monitor screen sizes can be different, meaning the center coordinate will be different for almost all computers.

HERES MY QUESTION: How would I get the center coordinate of the computer monitor running the swing application?

有帮助吗?

解决方案

How would I get the center coordinate of the computer monitor running the swing application?

You can get the center coordinate with java.awt.Toolkit:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = screenSize.width/2;
int centerY = screenSize.height/2;

However, you don't need it.

Just use:

yourFrame.setLocationRelativeTo(null);

And it will be automatically centered

其他提示

Try it

    //call `setSize` first
    this.setSize(300, 600);

    Toolkit tk = this.getToolkit();
    Dimension dim = tk.getScreenSize();
    int x = (int) dim.getWidth() / 2 - this.getWidth() / 2;
    int y = (int) dim.getHeight() / 2 - this.getHeight() / 2;
    this.setLocation(x, y);

Here this represents JFrame class object.

JFrame will display in the center of the screen.

Query the Toolkit object.

  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  int centerX = screenSize.getWidth() / 2;
  int centerY = screenSize.getHeight() / 2;

Swing's documentation states that the window will be centered on screen if setRelativeTo is passed null.

  public void setLocationRelativeTo(Component c)

As stated in their docs:

"If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method."

So simply do:

frame.setLocationRelativeTo(null);

..since your question was really how to get it to open in the center, not how to get the center coordinate.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top