JFrame
Before explaining how to create a frame first let's have a quick overview of what is meant by a frame?
A frame is a primary window or a top-level window within which you would add your GUI components like Buttons,Text Fields, images etc.Thus a frame acts as a container for the user interface elements.
To create a frame you need to import the javax.swing library and extend the JFrame class.Have a look at the following program to understand how to create a frame.
Program
Firstframe.java
import javax.swing.*;
import java.util.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setTitle("My FirstFrame");
}
}
import java.util.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setTitle("My FirstFrame");
}
}
Myframe.java
import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
The above program shown is an simple example of creating a frame without enclosing any components in it.
If you compile and execute this program then you would see a simple window in the top-left corner of the screen as shown above.
If you want to know how to position a frame? click here..
You may also be interested in sizing a frame which is essential for a good user-interface design.
An Overview
There are certain methods do exist which are essential for creating a frame properly.
As you see,
setTitle(String obj)- used to set the title for the frame,the title should be a string object.
setSize(int width,int height)- It is also obvious that this method is used to set the size of the frame.If you do not specify the size of the frame then a frame of size 0x0 pixels will be generated.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)- This method is used to terminate the program when the user closes the frame.If this method is not used then when the user closes the frame then the window will disappear but the program would not get terminated.
setVisible(true)- This method is used to make the frame visible on the screen.By default this property of the frame is set to false.So if you do not set this property of a frame to be true manually,your frame will not be visible.
0 comments:
Post a Comment