hamel123
hamel123

Reputation: 304

Layouts Issue on Different Components?

I'm writing a gui program in which use flow layout to set components.I know this layout start from default center and goes left to right like this

enter image description here

I also know structure of all other layouts but i want to make a gui like this

enter image description here

All components in center.But layout use in that picture is null.I only want to know about how can we do that in these type of layout like border,flow etc.
Code :

     public class Main {

    public static void main(String[] args) {

        JFrame obj = new JFrame();
        obj.setTitle("My Frame");
        obj.setSize(800, 600);
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setLocationRelativeTo(null);

        JLabel l1 = new JLabel("Enter Name");
        l1.setFont(new Font("Tahoma", Font.PLAIN, 21));

        JTextField t1 = new JTextField(20);
        t1.setFont(new Font("Tahoma", Font.PLAIN, 16));

        JButton b1 = new JButton("Submit");

        obj.setLayout(new FlowLayout());
        obj.add(l1);
        obj.add(t1);
        obj.add(b1);

        obj.setVisible(true);

    }

}

Upvotes: 3

Views: 49

Answers (1)

camickr
camickr

Reputation: 324147

You could use a BoxLayout. Something like:

box.add(label);
box.add(textField);
box.add(button);
box.add(Box.createVerticalGlue());

You may have to play with the setAlignmentX(...) property to allow the components to be centered horizontally.

Read the section from the Swing tutorial on How to Use BoxLayout for more information and examples.

Or you could use a GridBagLayout. The tutorial also has a section on How to Use GridBagLayout.

Upvotes: 1

Related Questions