To center a JFrame on the screen in a Java Swing application, Create a project with your choice and create a JFrame in it. Once you successfully created the JFrame, on the top you should see 3 tabs Source, Design and History. Design your Jframe as you like. To edit the auto-generated code you must click on the source buttion.
By default when you run the JFrame it shows to the left top side of the screen, to make it appear in the center of the screen just set the property as shown in code below.
setLocationRelativeTo(null);
package com.ia;
public class TechInfoPick extends javax.swing.JFrame {
public TechInfoPick() {
initComponents();
setLocationRelativeTo(null);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setText("Set Your Jframe in Center");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(34, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(125, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TechInfoPick().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Here is more information about the code.
By setting the property to setLocationRelativeTo(null) – This line of code shows the frame to appear in the center of the screen. When you pass null as the argument, it causes the window to be placed in the center of the screen.
Make sure you put the piece of code in your constructor after the initComponents(); as shown in the code.
public TechInfoPick() {
initComponents();
setLocationRelativeTo(null);
}