user1408605
user1408605

Reputation: 45

Display JFrame Centred on main monitor when using dual screens

I am trying to write some code to center my main application JFrame in the center of the computer screen using Java. To do it I am using the code below, which divides the process into two part, this is just because I use the ScreenHeight and ScreenWidth for scaling purposes elsewhere in the class and they are properties of the class.

This code works, on my laptop and other single screen machines perfectly, but on my main machine, which is dual monitor, it places the screen in the centre of the workspace which puts half the dialogue box (which can be small) on each screen. It's in a method, so that I can call it each time the dialogue boxes size, is changed by the program.

I use the boolean Width value to keep the screen in the same location on the vertical axis, but to center it on the horizontal.

// Finds the size of the screen
private void find_ScreenSize() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension dim = toolkit.getScreenSize();
    ScreenHeight = dim.height;
    ScreenWidth = dim.width;
}

// Centres the dialogue box within the screen
private void centre_Frame(JFrame Frame, boolean Width) {
    find_ScreenSize();

    if (!Width) { // if you are not justifying on the X axis
        Frame.setLocation(Frame.getLocationOnScreen().x,
                ((ScreenWidth / 2) - (Frame.getWidth() / 2)));
    } else {
        Frame.setLocation(((ScreenWidth / 2) - (Frame.getWidth() / 2)),
                ((ScreenHeight / 2) - (Frame.getHeight() / 2)));
    }
}

I would like to be able to center the dialogue box in the center of the main/first screen on any multi screen computers. The dialogue boxes in my application, that I don't control the location of, manage to do what I am trying to do for example my JOptionPane and file open and save dialogues all work perfectly.

I am developing on Linux, but the application is for use on Linux and MS platforms.

Searching for this problem gives me lots of examples of the above but nothing that shows me how to do what I want, any help would be appreciated.

Thanks in advance for any help.

Upvotes: 3

Views: 3549

Answers (1)

Nivas
Nivas

Reputation: 18334

frame.setLocationRelativeTo(null);

should work (doc). At least it does on my multi monitor setup. Note that the window is always displayed on the center of the main monitor, even if the app is launched from the secondary monitor.

You can use GraphicsEnvironment.getCenterPoint to find the center point rather than calculating youselves.

If you want to display in a specific monitor, see Show JFrame in a specific screen in dual monitor configuration

Upvotes: 3

Related Questions