Home Tutorial Java Swing Java Swing : JFrame Example

 
 

Share on Google+Share on Google+
Java Swing : JFrame Example
Posted on: September 10, 2012 at 12:00 AM
Advertisement
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.setSize(300,200);
frame.setTitle("Creating frame");
frame.setVisible(true);
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);

frame.add(area);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

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 :

Advertisement

Related Tags for Java Swing : JFrame Example :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 10, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com