Search code examples
javaswinggrouplayout

Aligning GroupLayout in the center of screen in Java Swing?


So if i have a GUI like this:

import javax.swing.GroupLayout;
public class MyTest extends javax.swing.JFrame {

    public MyTest() {
        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("This is a sample GUI");

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);

        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 244, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 85, Short.MAX_VALUE)
        );

        pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyTest().setVisible(true);
            }
        });
    }   
}

Now when i run the program, it is aligned to (0,0) position on the top-left of the screen. Is there anyway i can align this to the center of the screen or to another custom position?
This works fine if i only use a frame without using GroupLayout, like with setLocation(left,top), but with this implementation, how can i change the default positioning of this GUI?


Solution

  • I guess you did answer the question but it wasn't that clear to me, regarding how to use it. Simply by calling below before pack(); was exactly what i was looking for:

    this.setLocation(500,300); //value left, top in pixes
    pack();  
    

    So basically what i needed to know was the exact use of setLocation(x,y); and that with the use of keyword "this", thank you.