1

I need to center two JFrame side by side on the screen (for instance as if they were a single frame centered).

To center a single JFrame I used the command:

frame.setLocationRelativeTo(null);

How can I resolve now?

dic19
  • 17,821
  • 6
  • 40
  • 69
mikelplhts
  • 1,181
  • 3
  • 11
  • 32

2 Answers2

3

You need to know three things...

  1. The available visible area of the screen
  2. The size of both windows...(this counts as two)

There are a few ways to get the screen size, but what you really want is the viewable area, the area within which it is safe to show windows...

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

This now tells you the area within which it is safe to show content, taking into consideration things like the taskbar/dock that some OS's have...

Next, you need to know the size of the window...

frameA.pack();
frameB.pack();

Dimension dimA = frameA.getSize();
Dimension dimB = frameB.getSize();

Now, you need to calculate the position of the windows...

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

And there you have it...

Now, having said all that, you might like to take a look at The Use of Multiple JFrames, Good/Bad Practice? and How to Use Split Panes

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks for the answer you helped me alot, even if this code don't work (for me), but I modified in my way and it works perfectly. That is a good or bad use multiple JFrame I would not know which side to take, although I would prefer (as user of the software) a single JFrame. I'm doing a teaching level, to learn something more. Anyway thanks again! – mikelplhts Nov 25 '14 at 00:05
0

You can manually set the position of your frame with #setLocation I think

Malik Dz
  • 11
  • 5