Sunday, November 24, 2013

How to create Frame in AWT

Frame: Frame encapsulates what is commonly thought of as a "window". Window is basic element of user interface. AWT provides Frame class to create and maintain windows.
Creating a frame or window is very simple, you just need to initialize an object of Frame class, set some properties and your window is ready to display. Frame class provides two constructors:
1. Frame()
2. Frame(String Title)
First constructor is used to initialize frame object and the second constructor is used to initialize the frame object with title (Title of the window).
Syntax:
Frame _frame = new Frame(); //for creating a window without title



Frame _frame = new Frame("Window Title"); // for creating window with title


after initializing frame object we can set height and width of the frame or window by setSize() method.

Syntax:
//setSize(int newWidth, int newHeigth);

_frame.setSize(200,300);


after setting the height and width of the frame we can display the form by calling show() method of class Frame.
_frame.show(); // it will display the frame on runtime


Here is the complete code for creating and displaying AWT Frame/ Window:
import java.awt.*; // importing awt package
class MyWindow
{
    Frame _frame;
    MyWindow()
    {
        _frame = new Frame("Window Title");

        _frame.setSize(200,300); // The setSize method will set the heigth and width

        _frame.show(); //the Show Method is used to show the Frame on screen
    }

    public static void main(String args[])
    {
        new MyWindow();
    }
}


Output of the above program will look like:
frm

No comments:

Post a Comment