Java 在屏幕中部设置2帧

Java 在屏幕中部设置2帧,java,swing,jframe,Java,Swing,Jframe,我需要在屏幕上将两个JFrame并排居中(例如,就好像它们是一个居中的单帧) 要使单个JFrame居中,我使用了以下命令: frame.setLocationRelativeTo(null); 我现在怎么解决呢?你需要知道三件事 屏幕的可用可见区域 两个窗口的大小…(计为两个) 有几种方法可以获得屏幕大小,但您真正想要的是可视区域,即可以安全显示窗口的区域 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironm

我需要在屏幕上将两个
JFrame
并排居中(例如,就好像它们是一个居中的单帧)

要使单个
JFrame
居中,我使用了以下命令:

frame.setLocationRelativeTo(null);

我现在怎么解决呢?

你需要知道三件事

  • 屏幕的可用可见区域
  • 两个窗口的大小…(计为两个)
  • 有几种方法可以获得屏幕大小,但您真正想要的是可视区域,即可以安全显示窗口的区域

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    // Use this if need to know about a device which is not the default...
    //GraphicsDevice lstGDs[] = ge.getScreenDevices();
    GraphicsDevice device = ge.getDefaultScreenDevice();
    GraphicsConfiguration cf = device.getDefaultConfiguration();
    Rectangle bounds = cf.getBounds();
    
    Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    
    Point pA = new Point(
                    bounds.x + ((bounds.width / 2) - dimA.width),
                    bounds.y + ((bounds.height- dimA.height) / 2));
    Point pB = new Point(
                    bounds.x + (bounds.width / 2),
                    bounds.y + ((bounds.height- dimB.height) / 2));
    
    这将告诉您显示内容的安全区域,同时考虑到一些操作系统所具有的任务栏/驳接等功能

    接下来,您需要知道窗口的大小

    frameA.pack();
    frameB.pack();
    
    Dimension dimA = frameA.getSize();
    Dimension dimB = frameB.getSize();
    
    现在,您需要计算窗口的位置

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    // Use this if need to know about a device which is not the default...
    //GraphicsDevice lstGDs[] = ge.getScreenDevices();
    GraphicsDevice device = ge.getDefaultScreenDevice();
    GraphicsConfiguration cf = device.getDefaultConfiguration();
    Rectangle bounds = cf.getBounds();
    
    Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    
    Point pA = new Point(
                    bounds.x + ((bounds.width / 2) - dimA.width),
                    bounds.y + ((bounds.height- dimA.height) / 2));
    Point pB = new Point(
                    bounds.x + (bounds.width / 2),
                    bounds.y + ((bounds.height- dimB.height) / 2));
    
    现在你有了它


    说了这么多之后,你可能想看看,然后你可以用#setLocation手动设置你的帧的位置,我想

    谢谢你的回答,你帮了我很多忙,即使这个代码(对我来说)不起作用,但我用我的方式修改了,它工作得很好。这是一个好的或坏的使用多JFrame我不知道采取哪一方,虽然我更喜欢(作为软件的用户)一个单一的JFrame。我在做一个教学级的课程,学习更多的东西。无论如何,再次感谢!