Search code examples
javaawtgridbaglayout

Creating a simple design in java using GrigBagLayout without using swing


I want to create this design using only GrigBagLayout without using swing and panel in this code.

1

Inorder to complete my assignment problem i just prepare the code for this this design but it is not perfectly arranged.

import java.awt.*;
class GridBagLayout {
    public static void main(String args[]) {

        Frame f = new Frame();
        f.setSize(400,600);
        f.setLayout(new GridLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        Label l = new Label("Name  ");
        gbc.gridx=1;        
        gbc.gridy=1;
        f.add(l,gbc);


        TextField t = new TextField();
        gbc.gridx=1;            
        gbc.gridy=0;
        f.add(t,gbc);


        Label l2 = new Label("Password ");
        gbc.gridx=0;                    
        gbc.gridy=1;
        f.add(l2,gbc);

        TextField t2 = new TextField();
         gbc.gridx=1;           
         gbc.gridy=1;
        f.add(t2,gbc);


        Button b = new Button("OK");
        gbc.gridx=1;
        gbc.gridy=1;
        f.add(b,gbc);

        f.setVisible(true);
    }
}  

So anyone can tell me about where my code is lacking to perfectly arranged.


Solution

  • I hope your Assignment work should be based on GridBagLayout

    GridBagLayout

    so why you are using

    • f.setLayout(new GridLayout());

    Instead of using correct Layout

    f.setLayout(new GridBagLayout);

    import java.awt.*;
        class GridBagLayout
        {
            public static void main(String[] args) {
                Frame f=new Frame();
                f.setSize(300,200);
                GridBagLayout gl = new GridBagLayout();
                f.setLayout(gl);
                GridBagConstraints g=new GridBagConstraints();
                g.gridx=0;
                g.gridy=0;
                f.add(new Label("Name") , g);
    
                g.gridy=1;
                f.add(new Label("Password") , g);
    
                g.gridx=1;
                g.gridy=0;
                f.add(new TextField(15) , g);
    
                g.gridy=1;
                g.gridx=1;
                f.add(new TextField(15) , g);       
    
                g.gridx=0;
                g.gridy=2;
                g.gridwidth=2;
                g.insets = new Insets(30,0,0,0);
                f.add(new Button("OK"),g);
    
                f.setVisible(true);
            }
        }
    

    As GridBagLayout divides a container into a grid of equally sizwd cells and it requires lot of information to know where to put a component that's why i used gridx/y ,insets etc for proper arrangements of your labels and texfields.

    [Make your basics strong about java awt concepts ][1]

    [1]: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html