-1

I'm not sure how i should center this. I tried to use locationRelativeTo null but the gameBoard stays in the top left corner. But i need to center it.

 public static void main(String[] args) {
        JFrame game = new JFrame();
        game.setTitle("Game2048");
        game.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        game.setSize(420, 700);
        game.setResizable(false);
        game.add(new Game2048());
        // help here >>>>  game.setLocation();    
        game.setVisible(true);
    }
Mujammil Ahamed
  • 1,454
  • 4
  • 24
  • 50
  • Do you want to center an object in the JFrame or do you want to center the JFrame on the screen? – bachph Aug 11 '17 at 09:03
  • Only the object that i added. – Michel Atwood Aug 11 '17 at 09:15
  • 1
    Possible duplicate to ["How to set JFrame to appear centered, regardless of monitor resolution?"](https://stackoverflow.com/questions/2442599/how-to-set-jframe-to-appear-centered-regardless-of-monitor-resolution) – Thomas Fritsch Aug 11 '17 at 10:01

3 Answers3

1

See the javadoc of method setLocationRelativeTo(Component):

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.

That means, you can see simply use

game.setLocationRelativeTo(null);

and your JFrame game will be placed in the center of the screen.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
1

You can center two things here. First of all you can center the complete program window. This should be possible with

game.setLocationRelativeTo(null);

The second thing to center is the component in the JFrame, in your case the Game2048 component. Therefore I can recommend the tutorial A Visual Guide to Layout Managers

When it comes to dimensions it isn't always simple to understand how they're used in Swing.

I would recommend you set your dimensions in the component Game2048 and let the JFrame apply the dimensions.

If you use a JPanel you could also use the setAlignment methods

panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
bachph
  • 153
  • 1
  • 12
1

Only the object that i added.

Then the easiest way is to use a GridBagLayout for the content pane of the frame (instead of the default BorderLayout).

//game.add(new Game2048());
game.setLayout( new GridBagLayout() );
game.add(new Game2048, new GridBagConstraints());

Using the default constraints will cause the component to be centered in the space available.

Read the section from the Swing tutorial on How to use GridBagLayout for more information, especially the section on using the weightx/weighty constraints to understand why this works.

camickr
  • 321,443
  • 19
  • 166
  • 288