eli g
eli g

Reputation: 35

Any way to center the center of my JFrame?

I have my own main Frame and two JDialogs that pop up when someone chooses menu items.What i'd like is to have a Help dialog with some rules,suggestions etc. setLayout(null) and the Toolkit/Dimension do NOT help of course because they center the upper left corner of the frame/dialog in the screen . How could have the center of both the frame and dialog centered in a screen? Thanks in advance !

Upvotes: 2

Views: 172

Answers (5)

user2675678
user2675678

Reputation:

Try to add this to your code:
frameName.setLocationRelativeTo(null);
This will center the frame in your screen. One thing, make sure that you declare the size of your frame BEFORE this line of code. This line should be right before your setVisible declaration

Upvotes: 0

Dennis Kriechel
Dennis Kriechel

Reputation: 3749

setLocationRelativeTo(null) will only center the upper left corner if you Dialog has no size yet, e.g. if you call the .pack() method after the setLocationRelativeTo.

Small example:

    JFrame testFrame = new JFrame();
    JButton testButton = new JButton();
    testButton.setPreferredSize(new Dimension(500, 500));
    testFrame.add(testButton);
    testFrame.pack();
    testFrame.setLocationRelativeTo(null);
    testFrame.setVisible(true);

This will show an Frame which center is centered on the screen.

Upvotes: 2

splungebob
splungebob

Reputation: 5415

Do these in order:

1) Call pack() or setSize(...) on the frame/dialog to be shown (it should already have its components added at this point).

2) Then, call setLocationRelativeTo(null) on that container. Alternatively, you could call setLocationRelativeTo(parent) if the parent is offset and you want the dialog to be centered within the parent at its current location.

3) Then, call setVisible(true)

Upvotes: 3

Azad
Azad

Reputation: 5055

I think that will help:

frame.setLocationRelativeTo(null);

Usually we put a null as an argument, but you can put an argument of type Component, I prefer JOptionPane as it's always shows in center of the screen.

   frame.setLocationRelativeTo(new JOptionPane());
   //OR
   frame.setLocationRelativeTo(JOptionPane.getRootFrame());
  • And one hint for your, don't use null layout(absolute positioning), always use LayoutManagers.

Upvotes: 2

Jk1
Jk1

Reputation: 11443

Use this helper method to center any JFrame or JDialog:

public static Window centerFrame(Window win) {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        win.setLocation((int) ((dim.getWidth() - win.getWidth()) / 2), (int) ((dim.getHeight()  - win.getHeight()) / 2));
        return win;
    }

Upvotes: 1

Related Questions