Last active
June 25, 2019 16:14
-
-
Save samkcarlile/2c5a4131fadf0c62cea0a2202fbee0f3 to your computer and use it in GitHub Desktop.
[Center a JFrame] centers a jframe onscreen. #java #swing #jframe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CenteredJFrame { | |
public static void main(String[] args) { | |
JFrame frame = new JFrame(); | |
center(frame, 800, 600); | |
frame.add(new JButton("Bananas")); | |
frame.add(new JButton("Oranges")); | |
frame.add(new JButton("Apples")); | |
frame.setVisible(true); | |
} | |
/** | |
* Sets the width and height of a {@link JFrame} and centers it on the screen | |
* the screen. | |
*/ | |
public static void center(JFrame frame, int width, int height) { | |
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); | |
final int _x = (screen.width / 2) - (width / 2); | |
final int _y = (screen.height / 2) - (height / 2); | |
final Rectangle rect = new Rectangle(_x, _y, width, height); | |
frame.setBounds(rect); | |
final Dimension dims = new Dimension(width, height); | |
frame.setMinimumSize(dims); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment