Clue Lin
Clue Lin

Reputation: 7

Windows 10 java gui jframe over bound

I have some issue in Java GUI.

this is my original code

public class GUI extends JFrame{

public GUI(){

}

public static void main(String[] args){
    GUI gui = new GUI();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setSize(500, 400);
    gui.setVisible(true);
    gui.setLayout(new BorderLayout());

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    gui.setLocation(dim.width / 2 - gui.getSize().width / 2, dim.height / 2 - gui.getSize().height / 2);


}

}

and this is result

JFrame Over Bound

My OS is windows 10.

Could it be a problem?

Could someone please tell me how to solve this?

another pic

the problem is size of title bar and contents is different.

Thanks.

Upvotes: 0

Views: 999

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Always call setVisible(true) last and always pack your GUI. For example:

import java.awt.*;
import javax.swing.*;

public class GUI extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GUI gui = new GUI();
            gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            gui.setPreferredSize(new Dimension(500, 400));
            gui.setLayout(new BorderLayout());
            gui.pack();
            gui.setLocationRelativeTo(null);
            gui.setVisible(true);
        });
    }
}

and incorporating MeBigFatGuy's important recommendation: remember to always create the GUI on the Swing event thread.

Upvotes: 1

Related Questions