Java


Java Tutorial


Admission Enquiry Form

  

Java Swing JFrame

Java Swing JFrame

Jframe is a very basics component in java swing package. The most common Swing container for Java applications is the javax.swing.The JFrame class is an abstract class.The JFrame inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.
JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method.Here int is used for EXIT_ON_CLOSE.

Constructors used with JFrame

Type of Constructor Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(String title) It creates a new, initially invisible Frame with the specified title.



The following example creates a frame with Compuhelp as the text on the frame.

Example

JFrame frm=new JFrame("Compuhelp");

Basic Methods of JFrame class :

Method NameDescription
void setLayout(LayoutManager manager)Sets the LayoutManager.
void setSize(width,height)This method is used to set the height and width of a frame.
void setVisible(Boolean b)This method is used to set the visibility of a frame.
void setTitle(String str)This method is used to set the title of a frame.
void setEnabled(boolean bl)This method is used to enable or disable the frame.
Graphics getGraphics()Creates a graphics context for this component.
void remove(Component comp)Removes the specified component from the container.
void setDefaultCloseOperation(int operation)Sets the operation that will happen by default when the user initiates a "close" on this frame.
void setIconImage(Image image)Sets the image to be displayed as the icon for this window.
void setBounds(x, y, width, height)This method is used to set x,y cordinates and height,width of the frame.



Example of JFrame

import javax.swing.*;
public class FrameExample
{
public static void main(String[] args)
{
JFrame frm=new JFrame();
frm.setLayout(null);
frm.setSize(250,200);
frm.setVisible(true);
frm.setTitle("Welcome to Compuhelp");
frm.setBounds(100, 100, 500, 200);
frm.setEnabled(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frm.setExtendedState(JFrame.MAXIMIZED_BOTH);
}//end of main method
}//end of class



Output:

The code above will display :