Reputation: 7
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
My OS is windows 10.
Could it be a problem?
Could someone please tell me how to solve this?
the problem is size of title bar and contents is different.
Thanks.
Upvotes: 0
Views: 999
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