Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center an object in java

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);

        }
}
like image 298
user1241388 Avatar asked Dec 05 '25 15:12

user1241388


1 Answers

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);

        }
}
like image 141
Vishal K Avatar answered Dec 07 '25 05:12

Vishal K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!