如何在中心屏幕中定位表单?

时间:2022-11-11 12:39:21

I'm a .Net developer but somehow I was task to create a simple application in java for some extra reason. I was able to create that application but my problem is how can i center the form in the screen when the application is launched?

我是一名.Net开发人员,但不知何故,我的任务是在java中创建一个简单的应用程序,原因有些。我能够创建该应用程序,但我的问题是如何在应用程序启动时将窗体置于屏幕中心?

Here is my code:

这是我的代码:

private void formWindowActivated(java.awt.event.WindowEvent evt) 
{
        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the window
        this.setLocation(x, y);
}

The code above works fine but the problem is I've seen the form moving from the topleft most to center screen. I also tried adding that code in formWindowOpened event and still shows same action. Is there a better way for this? Just like in .NET Application there is a CenterScreen Position. Or if the code above is correct, on what Event will i put it?

上面的代码工作正常,但问题是我已经看到表单从最顶层移动到中心屏幕。我还尝试在formWindowOpened事件中添加该代码,并仍然显示相同的操作。有更好的方法吗?就像在.NET应用程序中一样,有一个CenterScreen Position。或者,如果上面的代码是正确的,我将把它放在什么事件上?

Thanks for reading this.

感谢您阅读本文。

9 个解决方案

#1


97  

Simply set location relative to null after calling pack on the JFrame, that's it.

在JFrame上调用pack之后,只需设置相对于null的位置即可。

e.g.,

例如。,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

#2


8  

The following example centers a frame on the screen:

以下示例在屏幕上居中显示框架:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

为了在屏幕上居中框架,我们需要获得本地图形环境。从这个环境,我们确定中心点。结合框架尺寸,我们设法使框架居中。 setLocation()是将帧移动到中心位置的方法。

Note that this is actually what the setLocationRelativeTo(null) does:

请注意,这实际上是setLocationRelativeTo(null)的作用:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

#3


2  

Change this:

改变这个:

public FrameForm() { 
    initComponents(); 
}

to this:

对此:

public FrameForm() {
    initComponents();
    this.setLocationRelativeTo(null);
}

#4


1  

public class Example extends JFrame {

public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size

public Example(){

      init();

}

private void init() {

    try {
        UIManager
                .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

        SwingUtilities.updateComponentTreeUI(this);
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(WIDTH, HEIGHT);

        setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
                (int) (dimension.getHeight() / 2 - HEIGHT / 2));


    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

}
}

#5


0  

i hope this will be helpful.

我希望这会有所帮助。

put this on the top of source code :

把它放在源代码的顶部:

import java.awt.Toolkit;

and then write this code :

然后编写这段代码:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    int lebar = this.getWidth()/2;
    int tinggi = this.getHeight()/2;
    int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
    int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
    this.setLocation(x, y);
}

good luck :)

祝你好运 :)

#6


0  

Actually, you dont really have to code to make the form get to centerscreen.

实际上,你真的不需要编写代码来使表单进入中心屏幕。

Just modify the properties of the jframe
Follow below steps to modify:

只需修改jframe的属性按照以下步骤进行修改:

  • right click on the form
  • 右键单击表单
  • change FormSize policy to - generate resize code
  • 将FormSize策略更改为 - 生成调整大小代码
  • then edit the form position X -200 Y- 200
  • 然后编辑表格位置X -200 Y-200

You're done. Why take the pain of coding. :)

你完成了。为什么要承担编码的痛苦。 :)

#7


0  

If you use NetBeans IDE right click form then

如果您使用NetBeans IDE右键单击表单

Properties ->Code -> check out Generate Center

属性 - >代码 - >签出生成中心

#8


-2  

Using this Function u can define your won position

使用此功能,您可以定义您的赢家位置

setBounds(500, 200, 647, 418);

#9


-2  

Try using this:

试试这个:

this.setBounds(x,y,w,h);

#1


97  

Simply set location relative to null after calling pack on the JFrame, that's it.

在JFrame上调用pack之后,只需设置相对于null的位置即可。

e.g.,

例如。,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

#2


8  

The following example centers a frame on the screen:

以下示例在屏幕上居中显示框架:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

为了在屏幕上居中框架,我们需要获得本地图形环境。从这个环境,我们确定中心点。结合框架尺寸,我们设法使框架居中。 setLocation()是将帧移动到中心位置的方法。

Note that this is actually what the setLocationRelativeTo(null) does:

请注意,这实际上是setLocationRelativeTo(null)的作用:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

#3


2  

Change this:

改变这个:

public FrameForm() { 
    initComponents(); 
}

to this:

对此:

public FrameForm() {
    initComponents();
    this.setLocationRelativeTo(null);
}

#4


1  

public class Example extends JFrame {

public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size

public Example(){

      init();

}

private void init() {

    try {
        UIManager
                .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

        SwingUtilities.updateComponentTreeUI(this);
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(WIDTH, HEIGHT);

        setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
                (int) (dimension.getHeight() / 2 - HEIGHT / 2));


    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

}
}

#5


0  

i hope this will be helpful.

我希望这会有所帮助。

put this on the top of source code :

把它放在源代码的顶部:

import java.awt.Toolkit;

and then write this code :

然后编写这段代码:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    int lebar = this.getWidth()/2;
    int tinggi = this.getHeight()/2;
    int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
    int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
    this.setLocation(x, y);
}

good luck :)

祝你好运 :)

#6


0  

Actually, you dont really have to code to make the form get to centerscreen.

实际上,你真的不需要编写代码来使表单进入中心屏幕。

Just modify the properties of the jframe
Follow below steps to modify:

只需修改jframe的属性按照以下步骤进行修改:

  • right click on the form
  • 右键单击表单
  • change FormSize policy to - generate resize code
  • 将FormSize策略更改为 - 生成调整大小代码
  • then edit the form position X -200 Y- 200
  • 然后编辑表格位置X -200 Y-200

You're done. Why take the pain of coding. :)

你完成了。为什么要承担编码的痛苦。 :)

#7


0  

If you use NetBeans IDE right click form then

如果您使用NetBeans IDE右键单击表单

Properties ->Code -> check out Generate Center

属性 - >代码 - >签出生成中心

#8


-2  

Using this Function u can define your won position

使用此功能,您可以定义您的赢家位置

setBounds(500, 200, 647, 418);

#9


-2  

Try using this:

试试这个:

this.setBounds(x,y,w,h);