user4056465
user4056465

Reputation:

Centering a JFrame?

I'm using one of the methods to try to center my frame called

frame.setLocationRelativeTo(null);

but it's centering it by putting the upper-right corner of the frame in the center of the screen, and that's not what I wanted. I wanted to make it so that it centers the frame itself in the middle, or in other words, I want the center of the frame to the in the center of the screen. Is there any other methods to do this? Thanks for the help.

More codes below:

 @Override
public Dimension getPreferredSize() {
    return new Dimension(500, 500);
} //I'm using this method to override the Jframe and return the panel size

and I'm using the:

frame.pack(); 

method to make the Jframe fit whatever size the jpanel size is, which is why a size isn't created for the jframe. But even if I do create the size for the jframe, and use the setLocationRelativeTo(null) method, nothing changes.

Upvotes: 0

Views: 66

Answers (2)

Mshnik
Mshnik

Reputation: 7032

You can get the size of your screen with Toolkit.getDefaultToolkit().getScreenSize(). Assuming you're not using multiple displays, it's simple from there to set the location of your JFrame such that it is centered in the screen.

public static void main(String[] args){
    JFrame f = new JFrame();
    f.getContentPane().add(new JLabel("Label"), BorderLayout.CENTER);
    f.getContentPane().add(new JButton("Button"), BorderLayout.SOUTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();

    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    f.setLocation((screen.width - f.getWidth())/2, (screen.height - f.getHeight())/2);

    f.setVisible(true);
}

It is important that the pack() call happens before setLocation, or it might not be centered again.

You could even create a subclass of JFrame that re-centers itself whenever it packs, as such:

class CenteredFrame extends JFrame{
    @Override
    public void pack(){
        super.pack();
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screen.width - getWidth())/2, (screen.height - getHeight())/2);
    }
}

Upvotes: 0

Solid
Solid

Reputation: 95

Normally if you're using Java 1.4 or newer the method setLocationRelativeTo(null) should help. It's weird that it reacts like that, could you maybe post your java file so we can see what's wrong?

Also, you have to setSize() your frame BEFORE using the setLocationRelativeTo(null) method.

Kindly, Solid

Upvotes: 1

Related Questions