Core Java - [AWT GridLayout Manager]

♠ Posted by Unknown in at 11:43

GridLayout


The GridLayout manager arranges components in a grid(matrix) formation with the number of rows and columns defined by the constructor. The components are placed in the grid from left to right starting with the first row, then the second, and so on, in the order in which they are added.

The GridLayout manager has two constructors:
                 
                  public GridLayout(int rows, int columns)

This constructs a new GridLayout with the specified number of rows and columns.
                 
                  public GridLayout(int rows, int columns, int hGap, intvGap)

This constructs a new GridLayout with the specified number of rows and columns, along with
specified horizontal and vertical gaps between components.

Example:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class GridLayoutExample extends Applet implements ActionListener 
{
    TextField tfFirstValue, tfSecondValue, tfAnswer;
    Label lblFirstValue, lblSecondValue, lblAnswer;
    Button btnSum;
    Panel p1;
    Panel p2;
    public void init()
    {
            lblFirstValue = new Label("Enter First value : ");
            lblSecondValue = new Label("Enter Second Value : ");
            lblAnswer = new Label("The Answer : ");
            tfFirstValue = new TextField();
            tfSecondValue = new TextField();
            tfAnswer = new TextField();
            btnSum = new Button("Sum");
            p1 = new Panel(new GridLayout(3,2));
            p2 = new Panel(new GridLayout(3,1));
Image: Java GridLayout Example            add(p1);
            add(p2);
            p1.add(lblFirstValue);
            p1.add(tfFirstValue);
            p1.add(lblSecondValue);
            p1.add(tfSecondValue);
            p1.add(lblAnswer);
            p1.add(tfAnswer);
            p2.add(btnSum);
            btnSum.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae)
    {
            int a = Integer.parseInt(tfFirstValue.getText());
            int b = Integer.parseInt(tfSecondValue.getText());
            int c = a + b;
            tfAnswer.setText(Integer.toString(c));
    }
}


0 comments:

Post a Comment