2

I noticed that most of my swing GUIs would flicker right before they center themselves. This happened with almost any JFrame that I have made, I was wondering if there is a workaround. I usually call setVisible(true), then pack(), followed by setLocationRelativeTo(null). This makes it appear in the top right and then center it self. I know that the flicker is happening because it's taking time for each method call, but is there a workaround for this (To make it nice and smooth)?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
imbuedHope
  • 508
  • 3
  • 14

2 Answers2

7

This order (and these methods) are better:

  1. frame.pack();
  2. frame.setLocationByPlatform(true); // superior to centering
  3. frame.setVisible(true);

If you set a number of frames visible doing that, they might appear something like this:

And of course, without any flicker, wobble or shake. ;)


The problem with that (setLocationRelativeTo(null)) is that the GUIs top right corner is centered and not the entire JFrame.

The defualt size of a JFrame is 0x0 and it stays that way until pack() or setSize() (but use pack() as you are doing currently) is called. So if you ask for a 0x0 component to be centered on screen, the JRE will place the 'middle pixel' of the 0x0 sized component at the exact center of the screen.

Alternately if you pack it first it has the correct size, and the method will work as expected. E.G.

frame.pack();
frame.setLocationRelativeTo(null); // show my splash screen!
frame.setVisible(true);
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

You should do first setLocationRelativeTo(null) and then setVisible(true) in the end.

gprathour
  • 14,813
  • 5
  • 66
  • 90
  • The problem with that is that the GUIs top right corner is centered and not the entire JFrame. – imbuedHope Jan 27 '12 at 06:39
  • `pack()` should be called ***before*** `setLocationRelativeTo(null)` to make it centered. I guess that is what GP Singh meant. (But in my answer, I was more explicit about the order of method calls.) – Andrew Thompson Jan 27 '12 at 06:46
  • See also the edit to my answer, which will hopefully explain what is going on. – Andrew Thompson Jan 27 '12 at 06:58