How do I center an object in java

button, center, field, java, swing

Solution

Always add the components in a `Container` of the `JFrame`. Set the Layout of `Container` as `GridLayout`. For example You can change your code as follows:

import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Normal {
    public static void main(String[] args) {
        JFrame frame = new JFrame("test");
        JButton button = new JButton("why");
        JPanel panel = new JPanel();
        JTextField field= new JTextField();
        Container c = frame.getContentPane();
        c.setLayout(new GridLayout(3,1));//Devides the container in 3 rows and 1 column
        c.add(panel);//Add in first row
        c.add(button);//Add in second row
        c.add(field);//Add in third row
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        }
}

Problem

I want to make a simple program that will have one button and multiple fields. When I was planning this out in my head I wanted to use a gridlayout, or at least cent the button at first since I am learning. Here is what I have so far, my question that I am leading to is where do I put in my grid layout, or do I set the alignment center in the panel, frame or button? ``` import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Normal { public static void main(String[] args) { JFrame frame = new JFrame("test"); JButton button = new JButton("why"); JPanel panel = new JPanel(); JTextField field= new JTextField(); //button button.setSize(50, 50); //Field field.setSize(250, 25); //Frame frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.add(panel); frame.add(field); frame.add(button); } } ```

Original source