Every program with a Swing GUI must contain atleast one top level swing container and JFrame is the most commonly used top level container for creating GUI applications.
So in order to create frame, you will have to create an instance of class JFrame or a subclass of JFrame. When working with JFrame objects, the following steps are basically followed to get a JFrame window to appear on the screen.
1. Create an object of type JFrame.
2. Give the JFrame object a size or/and location using setSize () or setBounds () methods.
3. Make the JFrame object appear on the screen by calling setVisible () method.
JFrame Method
Method | Purpose |
void setTitle(String) | Sets a JFrame’s title using the String argument |
void setSize(int ,int) | Sets a JFrame’s size in pixels with the width and height as arguments |
void setSize(Dimension) | Sets a JFrame’s size using a Dimension class object, the Dimension(int ,int) constructor creates an object that represents both a width and a height |
String (getTitle) | Returns a JFrame’s title |
void setResizable(boolean) | Sets the JFrame to be resizable by passing true to the method, or sets the JFrame not to be resizable by passing false to the method |
boolean isResizable() | Returns true or false to indicate whether the JFrame is resizable |
void setVisible(boolean) | Sets a JFrame to be visible using the boolean argument true and invisible using the boolean aruement false |
void setBounds(int,int, int,int) | Overrides the default behaviour for the JFrame to be positioned in the upper-left corner of the computer screen’s desktop. The first two arguments are the horizontal and vertical positions of the JFrame’s upper-left corner on the desktop. The final two arguments set the width and height |
import javax.swing.*;
class JFrameJavaExample
{
public static void main(String args[])
{
JFrame frame = new JFrame("JFrame in Swing Java Example");
frame.setSize(300,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // display the frame
}
}