如何在Java中使窗口居中?

问题描述 投票:0回答:21

java.awt.Window
居中的最简单方法是什么,例如
JFrame
JDialog

java swing user-interface awt
21个回答
275
投票

来自此链接

如果您使用的是 Java 1.4 或更高版本, 你可以使用简单的方法 setLocationRelativeTo(null) 上 对话框、框架或窗口居中 它。


73
投票

这应该适用于所有版本的 Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}

42
投票

setLocationRelativeTo(null)
应在使用
setSize(x,y)
或使用
pack()
后调用。


27
投票

请注意,setLocationRelativeTo(null) 和 Tookit.getDefaultToolkit().getScreenSize() 技术仅适用于主显示器。如果您处于多显示器环境中,则在进行此类计算之前,您可能需要获取有关窗口所在的特定显示器的信息。

有时重要,有时不......

有关如何获取此信息的更多信息,请参阅GraphicsEnvironment javadocs


21
投票

Linux 上的代码

setLocationRelativeTo(null)

在多显示环境中,每次启动窗口时,将其置于随机位置。 还有代码

setLocation((Toolkit.getDefaultToolkit().getScreenSize().width  - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);

将窗口“切成两半”,将其放置在我的两个显示器之间的正中心。 我使用以下方法将其居中:

private void setWindowPosition(JFrame window, int screen)
{        
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] allDevices = env.getScreenDevices();
    int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;

    if (screen < allDevices.length && screen > -1)
    {
        topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[screen].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[screen].getDefaultConfiguration().getBounds().height;
    }
    else
    {
        topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[0].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[0].getDefaultConfiguration().getBounds().height;
    }

    windowPosX = ((screenX - window.getWidth())  / 2) + topLeftX;
    windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;

    window.setLocation(windowPosX, windowPosY);
}

使窗口出现在第一个显示屏的正中央。 这可能不是最简单的解决方案。

在 Linux、Windows 和 Mac 上正常工作。


6
投票

我终于使用 Swing GUI Forms 在 NetBeans 中使用了这堆代码,以便将主 jFrame 居中:

package my.SampleUIdemo;
import java.awt.*;

public class classSampleUIdemo extends javax.swing.JFrame {
    /// 
    public classSampleUIdemo() {
        initComponents();
        CenteredFrame(this);  // <--- Here ya go.
    }
    // ...
    // void main() and other public method declarations here...

    ///  modular approach
    public void CenteredFrame(javax.swing.JFrame objFrame){
        Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
        int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
        int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
        objFrame.setLocation(iCoordX, iCoordY); 
    } 

}

package my.SampleUIdemo;
import java.awt.*;

public class classSampleUIdemo extends javax.swing.JFrame {
        /// 
        public classSampleUIdemo() {
            initComponents(); 
            //------>> Insert your code here to center main jFrame.
            Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
            int iCoordX = (objDimension.width - this.getWidth()) / 2;
            int iCoordY = (objDimension.height - this.getHeight()) / 2;
            this.setLocation(iCoordX, iCoordY); 
            //------>> 
        } 
        // ...
        // void main() and other public method declarations here...

}

    package my.SampleUIdemo;
    import java.awt.*;
    public class classSampleUIdemo extends javax.swing.JFrame {
         /// 
         public classSampleUIdemo() {
             initComponents();
             this.setLocationRelativeTo(null);  // <<--- plain and simple
         }
         // ...
         // void main() and other public method declarations here...
   }

4
投票

下面是在现有窗口的顶部中心显示框架的代码。

public class SwingContainerDemo {

private JFrame mainFrame;

private JPanel controlPanel;

private JLabel msglabel;

Frame.setLayout(new FlowLayout());

  mainFrame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent windowEvent){
        System.exit(0);
     }        
  });    
  //headerLabel = new JLabel("", JLabel.CENTER);        
 /* statusLabel = new JLabel("",JLabel.CENTER);    
  statusLabel.setSize(350,100);
 */ msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);

  controlPanel = new JPanel();
  controlPanel.setLayout(new FlowLayout());

  //mainFrame.add(headerLabel);
  mainFrame.add(controlPanel);
 // mainFrame.add(statusLabel);

  mainFrame.setUndecorated(true);
  mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
  mainFrame.setVisible(true);  

  centreWindow(mainFrame);

}

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, 0);
}


public void showJFrameDemo(){
 /* headerLabel.setText("Container in action: JFrame");   */
  final JFrame frame = new JFrame();
  frame.setSize(300, 300);
  frame.setLayout(new FlowLayout());       
  frame.add(msglabel);

  frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent windowEvent){
        frame.dispose();
     }        
  });    



  JButton okButton = new JButton("Capture");
  okButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
  //      statusLabel.setText("A Frame shown to the user.");
      //  frame.setVisible(true);
        mainFrame.setState(Frame.ICONIFIED);
        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        final Dimension screenSize = Toolkit.getDefaultToolkit().
                getScreenSize();
        final BufferedImage screen = robot.createScreenCapture(
                new Rectangle(screenSize));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ScreenCaptureRectangle(screen);
            }
        });
        mainFrame.setState(Frame.NORMAL);
     }
  });
  controlPanel.add(okButton);
  mainFrame.setVisible(true);  

} public static void main(String[] args) 抛出异常 {

new SwingContainerDemo().showJFrameDemo();

}

以下是上述代码片段的输出:


3
投票

以下不适用于 JDK 1.7.0.07:

frame.setLocationRelativeTo(null);

它将左上角置于中心 - 与将窗口居中不同。另一种也不起作用,涉及frame.getSize()和dimension.getSize():

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);

getSize()方法继承自Component类,因此frame.getSize也返回窗口的大小。因此,从垂直和水平尺寸中减去垂直和水平尺寸的一半,找到放置左上角的 x,y 坐标,即可得到中心点的位置,最终也使窗口居中。不过,上面代码的第一行很有用,“Dimension...”。只需这样做即可将其居中:

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);

JLabel 设置屏幕尺寸。它位于 Oracle/Sun 站点的 java 教程中的 FrameDemo.java 中。我将其设置为屏幕尺寸的高度/宽度的一半。然后,我将左上角放置在屏幕尺寸距左侧 1/4 的位置,以及屏幕尺寸距顶部 1/4 的位置,将其居中。您可以使用类似的概念。


3
投票

frame.setLocationRelativeTo(null);

完整示例:

public class BorderLayoutPanel {

    private JFrame mainFrame;
    private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;

    public BorderLayoutPanel() {
        mainFrame = new JFrame("Border Layout Example");
        btnLeft = new JButton("LEFT");
        btnRight = new JButton("RIGHT");
        btnTop = new JButton("TOP");
        btnBottom = new JButton("BOTTOM");
        btnCenter = new JButton("CENTER");
    }

    public void SetLayout() {
        mainFrame.add(btnTop, BorderLayout.NORTH);
        mainFrame.add(btnBottom, BorderLayout.SOUTH);
        mainFrame.add(btnLeft, BorderLayout.EAST);
        mainFrame.add(btnRight, BorderLayout.WEST);
        mainFrame.add(btnCenter, BorderLayout.CENTER);
        //        mainFrame.setSize(200, 200);
        //        or
        mainFrame.pack();
        mainFrame.setVisible(true);

        //take up the default look and feel specified by windows themes
        mainFrame.setDefaultLookAndFeelDecorated(true);

        //make the window startup position be centered
        mainFrame.setLocationRelativeTo(null);

        mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
    }
}

2
投票

在尝试使用

setLocationRelativeTo(null)
setLocation(x,y)
将窗口居中后,您可能会忽略一些非常简单的事情,但最终结果有点偏离中心。

确保您在after调用

pack()
之后使用其中一种方法,因为您最终将使用窗口本身的尺寸来计算将其放置在屏幕上的位置。在调用
pack()
之前,尺寸并不是您想象的那样,因此会放弃使窗口居中的计算。希望这有帮助。


2
投票

示例:第 3 行的 myWindow() 内部是您需要将窗口设置在屏幕中央的代码。

JFrame window;

public myWindow() {

    window = new JFrame();
    window.setSize(1200,800);
    window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setBackground(Color.BLACK);
    window.setLayout(null); // disable the default layout to use custom one.
    window.setVisible(true); // to show the window on the screen.
}

2
投票

调用的顺序很重要:

第一-

pack();

第二 -

setLocationRelativeTo(null);

1
投票

以下代码将

Window
置于当前监视器的中心(即鼠标指针所在的位置)。

public static final void centerWindow(final Window window) {
    GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
    Rectangle r = screen.getDefaultConfiguration().getBounds();
    int x = (r.width - window.getWidth()) / 2 + r.x;
    int y = (r.height - window.getHeight()) / 2 + r.y;
    window.setLocation(x, y);
}

1
投票

你也可以试试这个。

Frame frame = new Frame("Centered Frame");
Dimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dimemsion.width/2-frame.getSize().width/2, dimemsion.height/2-frame.getSize().height/2);

0
投票

其实frame

.getHeight()
getwidth()
没有返回值,通过
System.out.println(frame.getHeight());
检查直接把宽度和高度的值放在中间就可以正常工作了。例如:如下

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();      
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);  

450 是我的框架宽度和高度


0
投票
public class SwingExample implements Runnable {

    @Override
    public void run() {
        // Create the window
        final JFrame f = new JFrame("Hello, World!");
        SwingExample.centerWindow(f);
        f.setPreferredSize(new Dimension(500, 250));
        f.setMaximumSize(new Dimension(10000, 200));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void centerWindow(JFrame frame) {
        Insets insets = frame.getInsets();
        frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
        frame.setVisible(true);
        frame.setResizable(false);

        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);
    }
}

0
投票

除了 Donal 的回答之外,我还想添加一个小计算,以确保 Java 窗口完全位于窗口的中心。不仅仅是the window is at the center of the window

“左上角”

public static void centreWindow(JFrame frame, int width, int height) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);

        // calculate perfect center
        int perf_x = (int) x - width/2;
        int perf_y = (int) y - height/2;

        frame.setLocation(perf_x, perf_y);
    }

0
投票

如果您想要 Java NetBeans 的简单答案:

右键单击 JFrame,转到属性,然后转到代码并选择生成中心选项。

看图片供参考: [1]:https://i.stack.imgur.com/RFXbL.png


0
投票

如果你想推动你的应用程序窗口的中心,你可以按照下面的方法解决。

int x = (Toolkit.getDefaultToolkit().getScreenSize().width) - getSize().width) / 2;
int y = (Toolkit.getDefaultToolkit().getScreenSize().height) - getSize().height) / 2;
setLocation(x,y);

getSize() 函数是应用程序框架大小... getScreenSize() 是您的电脑屏幕尺寸。


0
投票

我想修改Dónal的答案以适应多显示器设置:

public static void centerWindow(Window frame) {
    Rectangle bounds = frame.getGraphicsConfiguration().getBounds();
    Dimension dimension = bounds.getSize();
    int x = (int) (((dimension.getWidth() - frame.getWidth()) / 2) + bounds.getMinX());
    int y = (int) (((dimension.getHeight() - frame.getHeight()) / 2) + bounds.getMinY());
    frame.setLocation(x, y);
}

0
投票
private void centerThisWindow(int screen) {
    GraphicsDevice[] screens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    int i = (screen >= screens.length || 0 > screen) ? 0 : screen;
    Rectangle r = screens[i].getDefaultConfiguration().getBounds();
    setLocation(((r.width - getWidth()) / 2) + r.x, ((r.height - getHeight()) / 2) + r.y);
}
© www.soinside.com 2019 - 2024. All rights reserved.