1

I have a JPanel that is used to draw the menu for my game and a JFrame that it is added to, I have to add the menu to the middle of the frame so that it will look just as good on a higher resolution as on a lower. I have tried frame.add(menu, BorderLayout.CENTER) and menu.setLocation(windowW / 2, windowH / 2) but none of these options work. What is the easiest way to accomplish this on?

  • Use `LayoutManager`'s: ALWAYS! Don't call `setLocation/setSize/setBounds` as the LayoutManager's will change that anyway (that is their job). Google "Java Swing LayoutManager tutorial" and read the Oracle tutorial. You will quickly see the various possibilities – Guillaume Polet Jun 06 '13 at 13:29

2 Answers2

3

Position a JComponent at the center of a JFrame

use GridBaglayout without override GridBagConstraints, or BoxLayout then JComponent will be placed into center and isn't resizable with container

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I tried making it work with this code: `Box box = new Box(BoxLayout.X_AXIS); box.add(Box.createHorizontalGlue()); box.add(menu); box.add(Box.createHorizontalGlue()); frame.add(box);` – Java Programmer Jun 06 '13 at 14:27
  • It does place it so that the menu starts in the middle but it cuts the menu of so that it will only show 1/4 of the menu. How would I fix this? – Java Programmer Jun 06 '13 at 14:28
  • if I remove the second `box.add(Box.createHorizontalGlue());` it wont cut the menu of but then it wont be in the middle – Java Programmer Jun 06 '13 at 14:32
  • 1
    +1, using GridBagLayout is the easiest way to do this. @JavaProgrammer, you were given working examples. We don't know why your code doesn't work. You have a bug in your code. Post your `SSCCE` that demonstrates the problem. – camickr Jun 06 '13 at 15:14
  • @Java Programmer sorry everything is up to you, nobody knows whats code is dispayed on your sceen, shot to the dark == JFrame.setJMenu.... – mKorbel Jun 06 '13 at 15:48
  • got it to work when I changed the class from a JComponent to a JPanel, thanks – Java Programmer Jun 06 '13 at 15:53
  • don't forget that JPanel has FlowLayout pre_implemented in API:-) and JComponent haven't any layoutmanager, is required to add some.... – mKorbel Jun 06 '13 at 15:57
1

You need to call the method frame.setLocationRealtiveTo(null) or as parameter the window where the new frame should be referenced to.

EDIT: Think I understood it wrong. You want to add a component to a JFrame to the middle of all. Add instead a JPanel to the JFrame and add the component to the JPanel (BorderLayout.Center).

marc3l
  • 2,525
  • 7
  • 34
  • 62