Here is an example that shows this technique, the setLocationRelativeTo(null) method is called at the end of the constructor.
import java.awt.Dimension;Output
import java.awt.Toolkit;
import javax.swing.JFrame;
public class JFrame_center extends JFrame{
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame center");
frame.pack();
//retrieve screen size
SizeScreen size = Toolkit.getDefaultToolkit().getScreenSize();
int height = screensize.height;
int width = sizeScreen.width;
//size is half the length and height
frame.setSize(width/2, height/2);
//here we center our window
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
That's it! Our window is nicely aligned in the center of the screen. In this program the method has been called getScreenSize of the class java Toolkit to retrieve the size of the screen from which the program is running. This method is very efficient because it returns the dimension according to the user's screen.
Reference
Create a JFrame GUI with SWING
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...