Java Swing : JFrame Example


Java Swing : JFrame Example

In this section, you will learn how to create a frame in java swing.

In this section, you will learn how to create a frame in java swing.

Java Swing : JFrame Example

In this section, you will learn how to create a frame in java swing.

JFrame :

JFrame class is defined in javax.swing.JFrame. It uses JRootPane as its only child. Root pane provides content pane which holds all the non-menu components displayed by the JFrame. The content pane will always be non-null. If you will try to set content pane null then JFrame will throw an exception.

Methods : Following are some methods -

createRootPane() : This method is called by constructor to create your default rootPane.

getContentPane() : It returns object of contentPane for your frame.

getRootPane() : Its return type is JRootPane.It returns the object of rootPane for your frame.

remove(Component comp) : This method removes the given component from your container.

setContentPane(Container contentPane) : It sets the contentPane property.

Other methods are - addImpl(Component comp, Object constraints, int index), frameInit(), getAccessibleContext(), getDefaultCloseOperation(), getGlassPane(), getJMenuBar() etc..

Example :

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JTextArea;

class CreateFrame{
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setTitle("Creating frame");
JTextArea area=new JTextArea(10, 40);
Toolkit toolkit = frame.getToolkit();
Dimension dimension=toolkit.getScreenSize();
frame.setLocation(dimension.width/2 - frame.getWidth()/2,
dimension.height/2 - frame.getHeight()/2);


Description : The above example shows how to create frame by using JFrame swing. 
Create object of JFrame as - JFrame frame=new JFrame();
frame.setSize(300,200) -In this statement we are setting size of frame as width 300 and height 200.
setTitle() method sets title of your frame and you can make it visible by using method  frame.setVisible(true);
JTextArea  creates area for text. Toolkit are used to bind the various components to particular native toolkit implementations.
The Dimension class encapsulates the width and height of a component (in integer precision) in a single object.
By using add() method we can add the component to our frame.

Output :