0

I am busy creating an interface using Java/Swing and I want to make the interface generate in the center of the screen when it is run. I am not using Drag and Drop so I need to code this feature in. I found in other posts on here two ways this can be done:

One way was:

this.pack();
this.setLocationRelativeTo(null)

and the other was:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize()
this.setLocation(dim.width/6-this.getSize().width/5, dim.height/6-this.getSize().height/5);

Both of these options work in a sense the frame no longer generates in the top left corner of the screen but now it is generated in the bottom right of my screen with most of the frame cut off. The second option's values were originally set to 2 but the values 5 and 6 were the closest I could get the frame to appear in the center but it was still quite a bit off.

Is there any way I can fix this? Could it be a resolution issue?

Osiris93
  • 189
  • 1
  • 15
  • 1
    Ensure that `setVisible(true)` is called later. After `pack()` do not add to the height. If you are filling the frame, set a preferred height, and fix it, maybe per a JScrollPane. – Joop Eggen Jul 06 '15 at 08:38
  • I suggest using `setLocationByPlatform(true)`. It lets your OS decide where it should pop up. Centering the frame can sometimes be a problem. For example, you might accidentally open 2 frames, but not notice since they're stacked right behind each other. – Vince Jul 06 '15 at 08:54
  • I just tried what you suggested and it is still a bit off. Vertically speaking it appears to be in the center. Horizontally speaking it's still placing more towards the left rather than in the center. I also tried the `setLocationByPlatform(true)` coding but it made no difference. – Osiris93 Jul 06 '15 at 09:06
  • @Osiris93 using 5 and 6 does not make any sense. Unless you change the size of your frame after calling that code, it should work without any problem. Post an mcve for better help – Guillaume Polet Jul 06 '15 at 09:33
  • I know it should work. My friend here tested it on his desktop and laptop and the coding works perfectly. That's what I don't understand, as I know that the values for `this.setLocation(dim.width/6-this.getSize().width/5, dim.height/6-this.getSize().height/5);` have to be 2 as that is suppose to place it in the middle. – Osiris93 Jul 06 '15 at 09:45
  • As I said, could this not maybe be a screen setting issue with my laptop that could be screwing up functionality of the coding when it displays the interface? – Osiris93 Jul 06 '15 at 09:59
  • See also [Best practice for setting JFrame locations](http://stackoverflow.com/q/7777640/418556). – Andrew Thompson Jul 06 '15 at 21:54

0 Answers0