How to set a JFrame location beside another JFrame?

岁酱吖の 提交于 2019-12-11 03:14:38

问题


In Java, how could I set a JFrame to automatically go beside another JFrame?

So, say I have two JFrame objects, frameA and frameB, and when the program runs, it sets frameAs location to be in the middle of the screen by using:

setLocationRelativeTo(null);

Now what I want is to make frameB to be on the right side of frameA, so they would be right beside each other. (frameAs right side would be touching frameBs left side)

How would you do this?


回答1:


This is a test class I created to demonstrate an example of how it could be done. You use the f1.getX() + f1.getWidth() to find to correct location for the second frame.

public class Test
{

    public static void main (String[] args)
    {

        JFrame f1 = new JFrame();
        f1. setSize(100, 100);
        f1.setLocationRelativeTo(null);
        f1.setVisible(true);

        JFrame f2 = new JFrame();
        f2.setSize(100, 100);
        f2.setLocation(f1.getX() + f1.getWidth(), f1.getY());
        f2.setVisible(true);

    }

}



回答2:


How about something like:

final Rectangle bounds = frameA.getBounds();
frameB.setLocation(bounds.x + bounds.width, bounds.y);


来源:https://stackoverflow.com/questions/23039600/how-to-set-a-jframe-location-beside-another-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!