3

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
hhaslam11
  • 191
  • 2
  • 7
  • 24
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Apr 13 '14 at 06:21
  • *"How would you do this?"* Put the content of frame A in the `BorderLayout.LINE_START` and the content of frame B in the `BorderLayout.CENTER` of a frame 'C' which would be the single frame of the application. – Andrew Thompson Apr 13 '14 at 06:23

2 Answers2

5

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);

    }

}
yitzih
  • 3,018
  • 3
  • 27
  • 44
2

How about something like:

final Rectangle bounds = frameA.getBounds();
frameB.setLocation(bounds.x + bounds.width, bounds.y);
Josh M
  • 11,611
  • 7
  • 39
  • 49