0% found this document useful (0 votes)
3 views103 pages

Event Handling in Java

The document provides an overview of event handling in Java, detailing the types of events (foreground and background) and the Delegation Event model involving sources and listeners. It explains how to register listeners for various event types, outlines the methods associated with different listener interfaces, and describes three approaches for implementing event handling. Additionally, it includes examples of event handling through classes and anonymous classes, as well as mouse event handling using MouseListener and MouseMotionListener interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views103 pages

Event Handling in Java

The document provides an overview of event handling in Java, detailing the types of events (foreground and background) and the Delegation Event model involving sources and listeners. It explains how to register listeners for various event types, outlines the methods associated with different listener interfaces, and describes three approaches for implementing event handling. Additionally, it includes examples of event handling through classes and anonymous classes, as well as mouse event handling using MouseListener and MouseMotionListener interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 103

Event Handling in Java

Last Updated : 22 Aug, 2023





An event can be defined as changing the state of an object or
behavior by performing actions. Actions can be a button click,
cursor movement, keypress through keyboard or page scrolling,
etc.
The java.awt.event package can be used to provide various
event classes.
Classification of Events
 Foreground Events
 Background Events

Types of Events

1. Foreground Events
Foreground events are the events that require user interaction to
generate, i.e., foreground events are generated due to interaction
by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the
scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are
known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what
should happen after an event occur. To handle the events,
Java follows the Delegation Event model.
Delegation Event model
 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are


various sources like buttons, checkboxes, list, menu-item,
choice, scrollbar, text components, windows, etc., to
generate events.
 Listeners: Listeners are used for handling the events
generated from the source. Each of these listeners
represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with
the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to
register.
Event Classes in Java
Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred
ActionEvent ActionListener
like a button click or selecting an
item from the menu-item list.
Event Class Listener Interface Description

The adjustment event is emitted by


AdjustmentEvent AdjustmentListener
an Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size
changed or changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a
container object.

These are focus-related events,


FocusEvent FocusListener which include focus, focusin,
focusout, and blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on the
keyboard.

The events that occur due to the


MouseListener &
MouseEvent user interaction with the mouse
MouseMotionListener
(Pointing Device).

An event that specifies that the


MouseWheelEvent MouseWheelListener mouse wheel was rotated in a
component.

An event that occurs when an


TextEvent TextListener
object’s text changes.

An event which indicates whether a


WindowEvent WindowListener window has changed its status or
not.

Note: As Interfaces contains abstract methods which need to


implemented by the registered class to handle events.
Different interfaces consists of different methods which are
specified below.
Listener Interface Methods

ActionListener  actionPerformed()

AdjustmentListener  adjustmentValueChanged()

 componentResized()
 componentShown()
ComponentListener
 componentMoved()
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener  itemStateChanged()

 keyTyped()
KeyListener  keyPressed()
 keyReleased()

 mousePressed()
 mouseClicked()
MouseListener  mouseEntered()
 mouseExited()
 mouseReleased()

MouseMotionListene  mouseMoved()
r  mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

WindowListener  windowActivated()
 windowDeactivated()
 windowOpened()
Listener Interface Methods

 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate
an event.
2. The object of the respective event class is created
automatically after event generation, and it holds all
information of the event source.
3. The newly created object is passed to the methods of the
registered listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by
placing the event handling code in one of the below-specified
places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler
may throw errors due to the unavailability of some packages.
Event Handling Within Class
 Java

// Java program to demonstrate the


// event handling within the class

import java.awt.*;
import java.awt.event.*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}

Output
After Clicking, the text field value is set to GFG!

Explanation
1. Firstly extend the class with the applet and implement the
respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event.
i.e. ActionEvent by addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class
 Java

// Java program to demonstrate the


// event handling by the other class

import java.awt.*;
import java.awt.event.*;

class GFG1 extends Frame {

TextField textField;

GFG2()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
button.addActionListener(other);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}

 Java

/// import necessary packages


import java.awt.event.*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
gfgObj.textField.setText("Using Different Classes");
}
}
Output

Handling event from different class

Event Handling By Anonymous Class


 Java

// Java program to demonstrate the


// event handling by the anonymous class

import java.awt.*;
import java.awt.event.*;

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
// Registering component with listener anonymously
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("Anonymous");
}
});

// add Components
add(textField);
add(button);

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}

Output

Handling anonymously
MouseListener and MouseMotionListener in
Java
Last Updated : 22 Dec, 2022



MouseListener and MouseMotionListener is an interface in
java.awt.event package . Mouse events
are of two types. MouseListener handles the events when the
mouse is not in motion. While MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate.
There are five abstract functions that represent these five
events. The abstract functions are :

1. void mouseReleased(MouseEvent e) : Mouse key is


released
2. void mouseClicked(MouseEvent e) : Mouse key is
pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the
component
4. void mouseEntered(MouseEvent e) : Mouse entered
the component
5. void mousepressed(MouseEvent e) : Mouse key is
pressed
There are two types of events that MouseMotionListener can
generate. There are two abstract functions that represent these
five events. The abstract functions are :

1. void mouseDragged(MouseEvent e) : Invoked when a


mouse button is pressed in the component and dragged.
Events are passed until the user releases the mouse
button.
2. void mouseMoved(MouseEvent e) : invoked when the
mouse cursor is moved from one point to another within
the component, without pressing any mouse buttons.
The following programs are a illustration of MouseListener and
MouseMotionListener.
1. Program to handle MouseListener events

 Java
// Java program to handle MouseListener events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseListener {

// Jlabels to display the actions of events of mouseListener


// static JLabel label1, label2, label3;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");

// set the size of the frame


f.setSize(600, 100);

// close the frame when close button is pressed


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create a new panel


JPanel p = new JPanel();

// set the layout of the panel


p.setLayout(new FlowLayout());

// initialize the labels


label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener to the frame


f.addMouseListener(m);

// add labels to the panel


p.add(label1);
p.add(label2);
p.add(label3);

// add panel to the frame


f.add(p);

f.show();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user

// this function is invoked when the mouse is pressed


public void mousePressed(MouseEvent e)
{

// show the point where the user pressed the mouse


label1.setText("mouse pressed at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is released


public void mouseReleased(MouseEvent e)
{

// show the point where the user released the mouse click
label1.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse exits the component


public void mouseExited(MouseEvent e)
{

// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse enters the


component
public void mouseEntered(MouseEvent e)
{

// show the point through which the mouse entered the


frame
label2.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is pressed or


released
public void mouseClicked(MouseEvent e)
{

// getClickCount gives the number of quick,


// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label3.setText("mouse clicked at point:"
+ e.getX() + " "
+ e.getY() + "mouse clicked :" +
e.getClickCount());
}
}

Output :

Note : The following program might not run in an online


compiler please use an offline IDE
Let’s take another example on MouseListener,the question
is:
Q. Write an applet which displays x and y co-ordinate in it’s status
bar whenever the user click anywhere in the Applet window.
Ans.
Note: This code is with respect to Netbeans IDE.

 Java

//Program of an applet which


//displays x and y co-ordinate
//in it's status bar,whenever
//the user click anywhere in
//the applet window.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
//is current calling object) and
//second "this" represent
//listener(in this case it is GFG)
}
public void mouseClicked(MouseEvent m)
{
int x = m.getX();
int y = m.getY();
String str = "x =" +x+",y = "+y;
showStatus(str);
}

@Override
public void mousePressed(MouseEvent e) {

@Override
public void mouseReleased(MouseEvent e) {

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {

}
}

Output:

Output showing (x,y) in status bar

Modification: Now our aim is to improve above program so that


co-ordinates should display at that point only where click has
been made
Note: This code is with respect to Netbeans IDE.

 Java

//Co-ordinates should display


//at that point only wherever
//there is click on canvas

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
// is current calling object) and
// second "this" represent listener
//(in this case it is GFG)
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint(); // we have made this
//call because repaint() will
//call paint() method for us.
//If we comment out this line,
//then we will see output
//only when focus is on the applet
//i.e on maximising the applet window
//because paint() method is called
//when applet screen gets the focus.
//repaint() is a method of Component
//class and prototype for this method is:
//public void repaint()

public void mouseEntered(MouseEvent m)


//over-riding all the methods given by
// MouseListener
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
}
Output

Output showing (x,y) in canvas

Now one more unusual thing will come in output which is


that, we will not able to see previous co-ordinates.But why?
In Java, before calling paint() method, it calls one more method
which is update() and it do the following things:

1. it repaints the applet background with current color.


2. it then calls paint().
Now to see previous co-ordinates as well:
we have to over-ride update() method also and it’s prototype is
similar to paint().
Further Modification To see previous co-ordinates as well:
Note: This code is with respect to Netbeans IDE.

 Java

//Co-ordinates should display


//at that point only wherever
//there is click on canvas and also
//able to see the previous coordinates

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void update(Graphics g)
{
paint(g);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint();
}
public void mouseEntered(MouseEvent m)
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
}

Output

Output showing previous co-ordinate as well


2. Program to handle MouseMotionListener events

 Java

// Java Program to illustrate MouseMotionListener events


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseMotionListener {

// Jlabels to display the actions of events of


MouseMotionListener
static JLabel label1, label2;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseMotionListener");

// set the size of the frame


f.setSize(600, 400);

// close the frame when close button is pressed


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create new panel


JPanel p = new JPanel();

// set the layout of the panel


p.setLayout(new FlowLayout());

// initialize the labels


label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener to the frame


f.addMouseMotionListener(m);

// add labels to the panel


p.add(label1);
p.add(label2);

// add panel to the frame


f.add(p);

f.show();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position

// invoked when mouse button is pressed


// and dragged from one point to another
// in a component
public void mouseDragged(MouseEvent e)
{
// update the label to show the point
// through which point mouse is dragged
label1.setText("mouse is dragged through point "
+ e.getX() + " " + e.getY());
}

// invoked when the cursor is moved from


// one point to another within the component
public void mouseMoved(MouseEvent e)
{
// update the label to show the point to which the cursor
moved
label2.setText("mouse is moved to point "
+ e.getX() + " " + e.getY());
}
}

Output :
3. Java program to illustrate MouseListener and
MouseMotionListener events
simultaneously
 Java

// Java program to illustrate MouseListener


// and MouseMotionListener events
// simultaneously

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseMotionListener,
MouseListener {

// Jlabels to display the actions of events of


MouseMotionListener and MouseListener
static JLabel label1, label2, label3, label4, label5;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener and
MouseMotionListener");

// set the size of the frame


f.setSize(900, 300);

// close the frame when close button is pressed


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create new panel


JPanel p = new JPanel();
JPanel p1 = new JPanel();

// set the layout of the frame


f.setLayout(new FlowLayout());

JLabel l1, l2;

l1 = new JLabel("MouseMotionListener events :");

l2 = new JLabel("MouseLIstener events :");


// initialize the labels
label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

label4 = new JLabel("no event ");

label5 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener and MouseMotionListenerto the frame


f.addMouseMotionListener(m);
f.addMouseListener(m);

// add labels to the panel


p.add(l1);
p.add(label1);
p.add(label2);
p1.add(l2);
p1.add(label3);
p1.add(label4);
p1.add(label5);

// add panel to the frame


f.add(p);
f.add(p1);

f.show();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user

// MouseMotionListener events

// invoked when mouse button is pressed


// and dragged from one point to another
// in a component
public void mouseDragged(MouseEvent e)
{
// update the label to show the point
// through which point mouse is dragged
label1.setText("mouse is dragged through point "
+ e.getX() + " " + e.getY());
}

// invoked when the cursor is moved from


// one point to another within the component
public void mouseMoved(MouseEvent e)
{
// update the label to show the point to which the cursor
moved
label2.setText("mouse is moved to point "
+ e.getX() + " " + e.getY());
}

// MouseListener events

// this function is invoked when the mouse is pressed


public void mousePressed(MouseEvent e)
{

// show the point where the user pressed the mouse


label3.setText("mouse pressed at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is released


public void mouseReleased(MouseEvent e)
{

// show the point where the user released the mouse click
label3.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse exits the component


public void mouseExited(MouseEvent e)
{

// show the point through which the mouse exited the frame
label4.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse enters the
component
public void mouseEntered(MouseEvent e)
{

// show the point through which the mouse entered the


frame
label4.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is pressed or


released
public void mouseClicked(MouseEvent e)
{

// getClickCount gives the number of quick,


// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label5.setText("mouse clicked at point:"
+ e.getX() + " "
+ e.getY() + "mouse clicked :" +
e.getClickCount());
}
}

output :
MouseListener vs MouseMotionListener

 MouseListener: MouseListener events are invoked when


the mouse is not in motion and is stable . It generates
events such as mousePressed, mouseReleased,
mouseClicked, mouseExited and mouseEntered (i.e when
the mouse buttons are pressed or the mouse enters or
exits the component). The object of this class must be
registered with the component and they are registered
using addMouseListener() method.

 MouseMotionListener: MouseMotionListener events are


invoked when the mouse is in motion . It generates
events such as mouseMoved and mouseDragged (i.e
when the mouse is moved from one point to another
within the component or the mouse button is pressed and
dragged from one point to another ). The object of this
class must be registered with the component and they are
registered using addMouseMotionListener() method.
Java KeyListener in AWT
Last Updated : 07 Nov, 2023



The Java KeyListener in the Abstract Window Toolkit (AWT) is a
fundamental tool for achieving this. The KeyListener Interface is
found in “java.awt.event” package. In this article, we’ll explore
what the KeyListener is, and its declaration methods, and supply
examples with explanatory comments.
Java KeyListener in AWT
The KeyListener port in Java AWT is quite used to listen for
keyboard events, such as key presses and key releases. It allows
your program to respond to user input from the keyboard, which
is crucial for building interactive applications.
Declaring KeyListener
public interface KeyListener extends EventListener
Methods of Java KeyListener in AWT
The KeyListener port defines three methods that you must
implement:
Method Description

keyPressed(KeyEvent e) Invoked when a key is pressed down.

keyReleased(KeyEvent e) Called when a key is released.

Fired when a key press/release results in a


keyTyped(KeyEvent e) character.

Example of Java KeyListener


Example 1:
Below is the implementation of the Java KeyListener:
 Java

// Java program to demonstrate textfield and


// display typed text using KeyListener
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener {

private TextField textField;


private Label displayLabel;

// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());

// Create and add a TextField for text input


textField = new TextField(20);
textField.addKeyListener(this);
add(textField);

// Create and add a Label to display typed text


displayLabel = new Label("Typed Text: ");
add(displayLabel);

// Ensure the frame can receive key events


setFocusable(true);
setFocusTraversalKeysEnabled(false);

// Make the frame visible


setVisible(true);
}

// Implement the keyPressed method


@Override
public void keyPressed(KeyEvent e) {
// You can add custom logic here if needed
}

// Implement the keyReleased method


@Override
public void keyReleased(KeyEvent e) {
// You can add custom logic here if needed
}

// Implement the keyTyped method


@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
displayLabel.setText("Typed Text: " + textField.getText()
+ keyChar);
}

public static void main(String[] args) {


new KeyListenerExample();
}
}

Output:

Example 2:
Below is the implementation of Java KeyListener:
 Java

//Java program to demonstrate keyPressed,


// keyReleased and keyTyped method
import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame implements


KeyListener {

private TextField textField;


private Label displayLabel;

// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());

// Create and add a TextField for text input


textField = new TextField(20);
textField.addKeyListener(this);
add(textField);

// Create and add a Label to display typed text


displayLabel = new Label("Typed Text: ");
add(displayLabel);

// Ensure the frame can receive key events


setFocusable(true);
setFocusTraversalKeysEnabled(false);

// Make the frame visible


setVisible(true);
}

// Implement the keyPressed method


@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Pressed: " +
KeyEvent.getKeyText(keyCode));
}

// Implement the keyReleased method


@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Released: " +
KeyEvent.getKeyText(keyCode));
}

// Implement the keyTyped method


@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println("Key Typed: " + keyChar);
displayLabel.setText("Typed Text: " + textField.getText()
+ keyChar);
}

public static void main(String[] args) {


new KeyListenerExample();
}
}
Output:

Terminal Showing the Key Presses:

GUI, which stands for Graphical User Interface, is a user-friendly visual


experience builder for Java applications. It comprises graphical units like
buttons, labels, windows, etc. via which users can connect with an
application. Swing and JavaFX are two commonly used applications to
create GUIs in Java.
Elements of GUI:
A GUI comprises an array of user interface elements. All these elements are
displayed when a user is interacting with an application and they are as
follows:
1. Input commands such as buttons, check boxes, dropdown lists and text
fields.
2. Informational components like banners, icons, labels or notification dialogs.
3. Navigational units like menus, sidebars and breadcrumbs.
GUI in JAVA: Swing and JavaFX
As mentioned above, to create a GUI in Java, Swing and JavaFX are the
most commonly used applications. Swing was designed with a flexible
architecture to make the elements customizable and easy to plug-and-play
which is why it is the first choice for java developers while creating GUIs.
As far as JavaFX is concerned, it consists of a totally different set of graphic
components along with new features and terminologies.
Creating a GUI
The process of creating a GUI in Swing starts with creating a class that
represents the main GUI. An article of this class acts as a container which
holds all the other components to be displayed.
In most of the projects, the main interface article is a frame, i.e., the JFrame
class in javax.swing package. A frame is basically a window which is
displayed whenever a user opens an application on his/her computer. It has
a title bar and buttons such as minimize, maximize and close along with
other features.
The JFrame class consists of simple constructors such as JFrame() and
JFrame(String). The JFrame() leaves the frame’s title bar empty, whereas
the JFrame(String) places the title bar to a specified text.
Apart from the title, the size of the frame can also be customized. It can be
established by incorporating the setSize(int, int) method by inserting the
width and height desired for the frame. The size of a frame is always
designated in pixels.
For example, calling setSize(550,350) would create a frame that would be
550 pixels wide and 350 pixels tall.
Usually, frames are invisible at the time of their creation. However, a user
can make them visible by using the frame’s setVisible(boolean) method by
using the word ‘true’ as an argument.
The following are the steps to create GUI in Java
STEP 1: The following code is to be copied into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame jframe = new JFrame("GUI Screen"); //create
JFrame object

jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(400,400); //set size of GUI
screen
jframe.setVisible(true);
}
}

STEP 2: Save and compile the code as mentioned above and then run it.
STEP 3: Adding buttons to the above frame. To create a component in Java,
the user is required to create an object of that component’s class. We have
already understood the container class JFrame.
One such component to implement is JButton. This class represents the
clickable buttons. In any application or program, buttons trigger user actions.
Literally, every action begins with a click; like to close an application, the
user would click on the close button.

A swing can also be inserted, which can feature a text, a graphical icon or a
combination of both. A user can use the following constructors:

· JButton(String): This button is labelled with a specified text.


· JButton(Icon): This button is labelled with a graphical icon.
· JButton(String,Icon): This button is labelled with a combination of text
and icon.

The following code is to be copied into an editor:


import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame jframe = new JFrame("GUI Screen"); //create JFrame object
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(400,400); //set size of GUI screen
JButton pressButton = new JButton("Press"); //create JButton object
jframe.getContentPane().add(pressButton);
jframe.setVisible(true);
}
}

STEP 4: The above is to be executed. A big button will appear on the


screen.
STEP 5: A user can add two buttons to the frame as well. Copy the code
given below into an editor.

import javax.swing.*;

class gui{

public static void main(String args[]){

JFrame jframe = new JFrame("GUI Screen");

jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jframe.setSize(400,400);

JButton firstButton = new JButton("First


Button"); //create firstButton object

JButton secondButton = new JButton("Second


Button"); //create secondButton object

jframe.getContentPane().add(firstButton);

jframe.getContentPane().add(secondButton);

jframe.setVisible(true);

}
STEP 6: Save, compile and run the above code.
STEP 7: Unpredicted output = ? It means that the buttons are getting
overlapped.
STEP 8: A user can create chat frames as well. Below is an example of the
same:

The following is the code for creating a chat frame:

import javax.swing.*;

import java.awt.*;

class gui {

public static void main(String args[]) {

//Create the Frame

JFrame jframe = new JFrame("Chat Screen");

jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jframe.setSize(400, 400);
// create two menubar button FILE and HELP

JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("FILE");

JMenu helpMenu = new JMenu("Help");

menuBar.add(fileMenu);

menuBar.add(helpMenu);

// create two more option in FILE button

JMenuItem fileMenu1 = new JMenuItem("new file");

JMenuItem fileMenu2 = new JMenuItem("Save as");

fileMenu.add(fileMenu1);

fileMenu.add(fileMenu2);

// Text Area at the Center

JTextArea textArea = new JTextArea();

//Create the panel at bottom and add label,


textArea and buttons

JPanel panel = new JPanel(); // this panel is not


visible in output

JLabel label = new JLabel("Please Enter Text");

JTextField textField = new JTextField(15); //


accepts upto 15 characters

JButton btn_send = new JButton("Send");


JButton btn_reset = new JButton("Reset");

panel.add(label); // Components Added using Flow


Layout

panel.add(textField);

panel.add(btn_send);

panel.add(btn_reset);

//Adding Components to the frame.

jframe.getContentPane().add(BorderLayout.SOUTH,
panel);

jframe.getContentPane().add(BorderLayout.NORTH,
menuBar);

jframe.getContentPane().add(BorderLayout.CENTER,
textArea);

jframe.setVisible(true);

Conclusion
It can be concluded that creating GUI in Java is a very easy and user-friendly
process as the Java applications provide customization according to the
requirements of the user. To learn more about Java, and to become an
expert in Java development go to NIIT and check out the courses that give
great insight on Java.

Introduction to Java Swing


Last Updated : 11 Jul, 2024



Swing is a Java Foundation Classes [JFC] library and an extension
of the Abstract Window Toolkit [AWT]. Java Swing offers much-
improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-
and-drop support.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI]
components as AWT and is part of the standard Java distribution.
By today’s application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components
required for developing complex GUIs required in modern
commercial applications. The AWT component set has quite a few
bugs and does take up a lot of system resources when compared
to equivalent Swing resources. Netscape introduced its Internet
Foundation Classes [IFC] library for use with Java. Its Classes
became very popular with programmers creating GUI’s for
commercial applications.
 Swing is a Set of API (API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract
Window Toolkit) 5:00 – 5:30 pm
 Includes New and improved Components that have been
enhancing the looks and Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone
swing GUI Apps as Servlets and Applets
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the
Swing is built on top of the AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and
The Swing Components are lightweight.
 Swing Supports a Pluggable look and feel and Swing
provides more powerful components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed
pane, etc.
 Further Swing Follows MVC.
Difference between Java Swing and Java
AWT
There are certain points from which Java Swing is different than
Java AWT as mentioned below:
Java AWT Java Swing

Swing is a part of Java Foundation


Java AWT is an API to develop GUI
Classes and is used to create various
applications in Java.
applications.

Components of AWT are heavy The components of Java Swing are


weighted. lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require java.awt Swing components requires javax.swing


package. package.

To know more about the topic, refer to Java Swing vs Java AWT.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI
components that simplify desktop Applications. Many
programmers think that JFC and Swing are one and the same
thing, but that is not so. JFC contains Swing [A UI component
package] and quite a number of other items:
 Cut and paste: Clipboard support.
 Accessibility features: Aimed at developing GUIs for users
with disabilities.
 The Desktop Colors Features were first introduced in Java
1.1
 Java 2D: it has Improved colors, images, and text support.
Features Of Swing Class
 Pluggable look and feel.
 Uses MVC architecture.
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane,
JScollPane, etc.
 Java is a platform-independent language and runs on any
client machine, the GUI look and feel, owned and
delivered by a platform-specific O/S, simply does not
affect an application’s GUI constructed using Swing
components.
 Lightweight Components: Starting with the JDK 1.1, its
AWT-supported lightweight component development. For
a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing
components have their own view supported by Java’s look
and feel classes.
 Pluggable Look and Feel: This feature enable the user
to switch the look and feel of Swing components without
restarting an application. The Swing library supports
components’ look and feels that remain the same across
all platforms wherever the program runs. The Swing
library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
 Highly customizable – Swing controls can be
customized in a very easy way as visual appearance is
independent of internal representation.
 Rich controls– Swing provides a rich set of advanced
controls like Tree TabbedPane, slider, colorpicker, and
table controls.
Swing Classes Hierarchy

The MVC Connection


 In general, a visual component is a composite of three
distinct aspects:
1. The way that the component looks when rendered
on the screen.
2. The way such that the component reacts to the
user.
3. The state information associated with the
component.
Over the years, one component architecture has proven

itself to be exceptionally effective: – Model-View-
Controller or MVC for short.
 In MVC terminology, the model corresponds to the state
information associated with the Component.
 The view determines how the component is displayed on
the screen, including any aspects of the view that are
affected by the current state of the model.
 The controller determines how the component reacts to
the user.
The simplest Swing components have capabilities far
beyond AWT components as follows:
 Swing buttons and labels can be displaying images
instead of or in addition to text.
 The borders around most Swing components can be
changed easily. For example, it is easy to put a 1-pixel
border around the outside of a Swing label.
 Swing components do not have to be rectangular.
Buttons, for example, can be round.
 Now The Latest Assertive technologies such as screen
readers can easily get information from Swing
components. Example: A screen reader tool can easily
capture the text that is displayed on a Swing button or
label.
Example of Java Swing Programs
Example 1: Develop a program using label (swing) to display the
message “GFG WEB Site Click”:
Java
// Java program using label (swing)
// to display the message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();

// Creating instance of JButton


JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height


button.setBounds(150, 200, 220, 50);
// adding button in JFrame
frame.add(button);

// 400 width and 500 height


frame.setSize(500, 600);

// using no layout managers


frame.setLayout(null);

// making the frame visible


frame.setVisible(true);
}
}

Output:
Example 2: Write a program to create three buttons with caption
OK, SUBMIT, CANCEL.
Java
// Java program to create three buttons
// with caption OK, SUBMIT, CANCEL
import java.awt.*;

class button {
button()
{
Frame f = new Frame();

// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);

// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);

// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String a[]) { new button(); }


}

Output:

Output of Example 2
Example 3: Program to Add Checkbox in the Frame
Java
// Java Swing Program to Add Checkbox
// in the Frame
import java.awt.*;

// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();

Label l1 = new Label("Select known Languages");

l1.setBounds(100, 50, 120, 80);


f.add(l1);

// CheckBox created
Checkbox c2 = new Checkbox("Hindi");
c2.setBounds(100, 150, 50, 50);
f.add(c2);

// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);

// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String ar[]) { new Lan(); }


}

Output:
Output of Example 3

Components of Swing Class the task’s


percentage
Class Description

A Component is the Abstract base class


for about the non-menu user-interface
Component controls of Java SWING. Components
are representing an object with a
graphical representation.

A Container is a component that can


Container
container Java SWING Components

JComponent A JComponent is a base class for all


Class Description

swing UI Components In order to use a


swing component that inherits from
JComponent, the component must be in
a containment hierarchy whose root is a
top-level Java Swing container.

A JLabel is an object component for


JLabel
placing text in a container.

JButton This class creates a labeled button.

A JColorChooser provides a pane of


JColorChooser controls designed to allow the user to
manipulate and select a color.

A JCheckBox is a graphical (GUI)


JCheckBox component that can be in either an on-
(true) or off-(false) state.

The JRadioButton class is a graphical


(GUI) component that can be in either
JRadioButton
an on-(true) or off-(false) state. in the
group

A JList component represents the user


JList
with the scrolling list of text items.

A JComboBox component is Presents


JComboBox the User with a show up Menu of
choices.

A JTextField object is a text component


JTextField that will allow for the editing of a single
line of text.

A JPasswordField object it is a text


JPasswordField component specialized for password
entry.

JTextArea A JTextArea object is a text component


Class Description

that allows for the editing of multiple


lines of text.

A ImageIcon control is an
Imagelcon implementation of the Icon interface
that paints Icons from Images

A JScrollbar control represents a scroll


JScrollbar bar component in order to enable users
to Select from range values.

JOptionPane provides set of standard


JOptionPane dialog boxes that prompt users for a
value or Something.

A JFileChooser it Controls represents a


JFileChooser dialog window from which the user can
select a file.

As the task progresses towards


JProgressBar completion, the progress bar displays
the tasks percentage on its completion.

A JSlider this class is letting the user


graphically (GUI) select by using a
JSlider
value by sliding a knob within a
bounded interval.

A JSpinner this class is a single line


input where the field that lets the user
JSpinner
select by using a number or an object
value from an ordered sequence.
Java AWT Panel
Last Updated : 13 Nov, 2023



In Java’s Abstract Window Toolkit (AWT), the Panel class is a
fundamental component for creating graphical user interfaces. It
offers a straightforward way to organize and group various GUI
elements. This article explores the Panel class in Java AWT,
covering its essential aspects, methods, and constructors, and
demonstrating its practical use through example code.
Class Declaration
public class Panel extends Container
The panel is a subclass of the Container class, which means it can
contain other AWT components.
Constructors of AWT Panel
Constructor Description

Creates a new panel with the default layout


Panel() manager.

Panel(LayoutManager Creates a new panel with the specified layout


layout) manager.

Methods of AWT Panel


Method Description

Adds the specified component to this


void add(Component comp) panel.

Returns the component at the specified


Component getComponent(int n) index.

Removes the specified component from


void remove(Component comp) this panel.

void removeAll() Removes all components from this panel.

void setLayout(LayoutManager
Sets the layout manager for this panel.
layout)
Example of AWT Panel
Below is the implementation of the above topic:
 Java

// Java Program to implement


// AWT Panel
import java.awt.*;
import java.awt.event.*;

// Driver Class
public class PanelExample {
// main function
public static void main(String[] args) {

Frame frame = new Frame("Java AWT Panel Example");


Panel panel1 = new Panel();
Panel panel2 = new Panel();

// Set the layout manager for panel1


panel1.setLayout(new FlowLayout());

// Add components to panel1


Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");

panel1.add(button1);
panel1.add(button2);

// Set background colors for panels


panel1.setBackground(Color.CYAN);
panel2.setBackground(Color.MAGENTA);

// Add panels to the frame


frame.add(panel1);
frame.add(panel2);

frame.setSize(400, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}

In this example, we create two panels (panel1 and panel2) and


add buttons to panel1. The setLayout method is used to specify
the layout manager for panel 1, and we set different background
colors for the panels. The Frame class is used to create the main
window for the GUI.
Output:

Output Screen:

Conclusion
The Panel class in Java AWT is a versatile tool around for
designing well-structured graphic user interfaces. By allowing the
grouping of components within panels, it simplifies and enhances
the GUI plan. This article introduced the Panel class, its methods,
and constructors, and provided an informative model. Armed with
this knowledge, you can in effect purchase the Panel class to
make more unionized and visually pleasing Java applications.
Java Swing – JPanel With Examples
Last Updated : 10 Nov, 2021



JPanel, a part of the Java Swing package, is a container that can
store a group of components. The main task of JPanel is to
organize components, various layouts can be set in JPanel which
provide better organization of components, however, it does not
have a title bar.
Constructors of JPanel
1. JPanel(): creates a new panel with a flow layout
2. JPanel(LayoutManager l): creates a new JPanel with
specified layoutManager
3. JPanel(boolean isDoubleBuffered): creates a new
JPanel with a specified buffering strategy
4. JPanel(LayoutManager l, boolean
isDoubleBuffered): creates a new JPanel with specified
layoutManager and a specified buffering strategy
Commonly used Functions of JPanel
1. add(Component c): Adds a component to a specified
container
2. setLayout(LayoutManager l): sets the layout of the
container to the specified layout manager
3. updateUI(): resets the UI property with a value from the
current look and feel.
4. setUI(PanelUI ui): sets the look and feel of an object
that renders this component.
5. getUI(): returns the look and feel object that renders this
component.
6. paramString(): returns a string representation of this
JPanel.
7. getUIClassID(): returns the name of the Look and feel
class that renders this component.
8. getAccessibleContext(): gets the AccessibleContext
associated with this JPanel.
Let us take a sample program in order to illustrate the use of
JPanel class by appending sequential execution snapshots of
outputs justifying the below program sets as follows:
Example:
 Java

// Java Program to Create a Simple JPanel


// and Adding Components to it

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Class 1
// Helper class extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2;

// Label to display text


static JLabel l;

// Main class
public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");

// Creating a panel to add buttons


JPanel p = new JPanel();
// Adding buttons and textfield to panel
// using add() method
p.add(b);
p.add(b1);
p.add(b2);
p.add(l);

// setbackground of panel
p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Example 2:
 Java

// Java Program to Create a JPanel with a Border Layout


// and Adding Components to It

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Main class
// Extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2, b3;

// Label to display text


static JLabel l;

// Main driver method


public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");
b3 = new JButton("button4");

// Creating a panel to add buttons


// and a specific layout
JPanel p = new JPanel(new BorderLayout());

// Adding buttons and textfield to panel


// using add() method
p.add(b, BorderLayout.NORTH);
p.add(b1, BorderLayout.SOUTH);
p.add(b2, BorderLayout.EAST);
p.add(b3, BorderLayout.WEST);
p.add(l, BorderLayout.CENTER);

// setbackground of panel
p.setBackground(Color.red);
// Adding panel to frame
f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Example 3:
 Java

// Java Program to Create a JPanel with a Box layout


// and Adding components to it

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Main class
// Extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2, b3;

// Label to display text


static JLabel l;

// Main drive method


public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");
b3 = new JButton("button4");

// Creating a panel to add buttons and


// textfield and a layout
JPanel p = new JPanel();

// Setting box layout


p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

// Adding buttons and textfield to panel


p.add(b);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(l);

// Setting background of panel


p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Henceforth, we are successfully able to generate buttons in our


panel.
Note: In the previous Program, border layout and Box Layout are
used. Different other layouts can be used to organize the
components in a definite pattern, such as card layout, grid layout,
etc.
Java JFrame
Last Updated : 17 Nov, 2023



Thе Java JFramе is an еssеntial componеnt of Java Swing, which
is a part of thе Java SWT(Standard Widgеt Toolkit). JFrame in
Java is a class that allows you to crеatе and manage a top-lеvеl
window in a Java application. It sеrvеs as thе main window for
GUI-basеd Java applications and providеs a platform-indеpеndеnt
way to crеatе graphical usеr intеrfacеs. In Java JFrame is a part
of javax.swing package. In this article, we will learn about Java
JFrame.
Constructor of Java JFrame
Constructor Description

This is the default constructor for


JFrame() JFrame. It creates a new frame with no
title

This constructor creates a new frame


JFrame(String title)
with the specified title.

This constructor creates a JFrame that


JFrame(GraphicsConfiguration gc) uses the specified graphics
configuration.

This constructor creates a JFrame with


JFrame(String title,
the specified title and using the
GraphicsConfiguration gc)
specified graphics configuration.

This constructor creates a JFrame with


JFrame(Rectangle bounds)
the specified bounds.

This constructor creates a JFrame with


JFrame(String title, Rectangle bounds)
the specified title and bounds.

Methods of Java JFrame


Methods Description

setTitle(String title) Sets the title of the JFrame.

setSize(int width, int height) Sets the size of the JFrame.

Sets the default close operation for the


JFrame. Common options include
setDefaultCloseOperation(int
JFrame.EXIT_ON_CLOSE,
operation)
JFrame.HIDE_ON_CLOSE, and
JFrame.DO_NOTHING_ON_CLOSE.

Sets the visibility of the JFrame. Pass true


setVisible(boolean b)
to make it visible and false to hide it.

Sets the layout manager for the JFrame,


setLayout(LayoutManager manager) which controls how components are
arranged within the frame.

add(Component comp) Adds a Swing component to the JFrame.

remove(Component comp) Removes a component from the JFrame.

Forces the layout manager to recalculate


validate() the layout of components within the
JFrame.

Controls whether the user can resize the


setResizable(boolean resizable)
JFrame.

Sets the icon (image) for the JFrame


setIconImage(Image image)
window.

Parent Classes of JFrame Methods


Java JFrame is the part of Java Swing and the classes from where
all the methods associated with JFrame are inherited are
mentioned below:
1. java.awt.Frame
2. java.awt.Container
3. java.awt.Window
4. javax.swing.JFrame
Some Fields for Java JFrame
Fields Description

A field that specifies the default


operation to perform when the user
EXIT_ON_CLOSE (int) closes the JFrame. It’s typically used
with the setDefaultCloseOperation()
method.

It is constant that specifies an operation


to perform when the user closes the
DISPOSE_ON_CLOSE (int)
JFrame.It disposes of the JFrame but
doesn’t exit the application.

Specifies that the JFrame should be


HIDE_ON_CLOSE (int) hidden but not disposed of when the user
closes it.

Indicates that no action should be taken


DO_NOTHING_ON_CLOSE (int)
when the user closes the JFrame.

Programs to implement JFrame


1. Java Program to demonstrate a simple JFrame
Below is the demonstration of the simple JFrame:
 Java

// Java Swing Program to demonstrate


// a simple JFrame
import javax.swing.JFrame;
import javax.swing.JLabel;

// Driver Class
public class MyJFrame {
// main function
public static void main(String[] args)
{
// Create a new JFrame
JFrame frame = new JFrame("My First JFrame");

// Create a label
JLabel label
= new JLabel("Geeks Premier League 2023");

// Add the label to the frame


frame.add(label);

// Set frame properties


frame.setSize(300,
200); // Set the size of the frame

// Close operation
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);

// Make the frame visible


frame.setVisible(true);
}
}

Output:

2. Java Program to Add a JMenuBar and JButton inside


the JFrame
Below is the Implementation of the Add a JMenuBar and JButton
inside the JFrame example:
 Java

// Java Swing Program to Add


// JMenuBar and JButton inside the JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Driver Class
public class JFrameExample {
// Main function
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);

// Create a menu bar


JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
menuBar.add(fileMenu);

// Create a panel with a button


JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
panel.add(button);

// Add action to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button
Clicked!");
}
});

// Create another panel with text


JPanel textPanel = new JPanel();
JLabel label = new JLabel("Geeks Premier League 2023");
textPanel.add(label);

// Set layout for the main frame


frame.setLayout(new BorderLayout());
frame.setJMenuBar(menuBar);
frame.add(panel, BorderLayout.CENTER);
frame.add(textPanel, BorderLayout.SOUTH);

frame.setVisible(true);
}
}

Output:
manage
The Layout managers enable us to control the way in which visual
components are arranged in the GUI forms by determining the size and
position of components within the containers.

Types of LayoutManager
There are 6 layout managers in Java

 FlowLayout: It arranges the components in a container like the words


on a page. It fills the top line from left to right and top to bottom.
The components are arranged in the order as they are added i.e. first
components appears at top left, if the container is not wide enough to
display all the components, it is wrapped around the line. Vertical and
horizontal gap between components can be controlled. The
components can be left, center or right aligned.
 BorderLayout: It arranges all the components along the edges or the
middle of the container i.e. top, bottom, right and left edges of the
area. The components added to the top or bottom gets its preferred
height, but its width will be the width of the container and also the
components added to the left or right gets its preferred width, but its
height will be the remaining height of the container. The components
added to the center gets neither its preferred height or width. It covers
the remaining area of the container.
 GridLayout: It arranges all the components in a grid of equally sized
cells, adding them from the left to right and top to bottom. Only
one component can be placed in a cell and each region of the grid will
have the same size. When the container is resized, all cells are
automatically resized. The order of placing the components in a cell is
determined as they were added.
 GridBagLayout: It is a powerful layout which arranges all the
components in a grid of cells and maintains the aspect ration of the
object whenever the container is resized. In this layout, cells may be
different in size. It assigns a consistent horizontal and vertical gap
among components. It allows us to specify a default alignment for
components within the columns or rows.
 BoxLayout: It arranges multiple components in either vertically or
horizontally, but not both. The components are arranged from left to
right or top to bottom. If the components are aligned horizontally,
the height of all components will be the same and equal to the largest
sized components. If the components are aligned vertically, the width
of all components will be the same and equal to the largest width
components.
 CardLayout: It arranges two or more components having the same
size. The components are arranged in a deck, where all the cards of
the same size and the only top card are visible at any time. The
first component added in the container will be kept at the top of the
deck. The default gap at the left, right, top and bottom edges are zero
and the card components are displayed either horizontally or
vertically.

Example
import java.awt.*;
import javax.swing.*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1,
gridLayoutPanel2, gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
setLayout(new BorderLayout()); // Set BorderLayout for JFrame
flowLayoutPanel1 = new JPanel();
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); //
Set FlowLayout Manager
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
flowLayoutPanel1.add(three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)); //
Set FlowLayout Manager
flowLayoutPanel2.add(bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);
gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout
Manager
gridLayoutPanel1.add(gridLayoutPanel2);
gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}

Learn Java in-depth with real-world projects through our Java certification
course. Enroll and become a certified expert to boost your career.

Output
Java AWT | FlowLayout
Last Updated : 25 Jun, 2018



FlowLayout is used to arrange components in a sequence one
after the other. The default layout of applet and panel is
FlowLayout.
Constructors :
1. FlowLayout(): It will Construct a new FlowLayout with
centered alignment.The horizontal and vertical gap will be
5 pixels.
2. FlowLayout(int align) : It will Construct a new
FlowLayout with given alignment.The horizontal and
vertical gap will be 5 pixels.
3. FlowLayout(int align, int HorizontalGap, int
VerticalGap ): It will Construct a new FlowLayout with
given alignment, the given horizontal and vertical gap
between the components.
4. JLabel(String text): It will create a JLabel instance with
the specified text.
Commonly used methods:
1. setTitle(String Text): This Method is used to set Title of
JFrame. The title you want to set is passed as a string.
2. getAlignment(): Returns the alignment for this layout.
3. setAlignment(int align): used to set the alignment for
this layout.
4. removeLayoutComponent(Component comp): Used
to remove the component passed as argument from the
layout.
Below programs will illustrate the Example of FlowLayout in java.
1. Program 1: The following program illustrates the use of
FlowLayout by arranging several JLabel components in a
JFrame, whose instance class is named as “Example”. We
create 5 JLabel components named “l1”, “l2″… “l5” and
then add them to the JFrame by the method this.add().
We set the title and bounds of the frame by method
setTitle and setBounds.
The layout is set by the method setLayout();
// Java program to show Example of FlowLayout.
// in java. Importing different Package.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Example extends JFrame {


// Declaration of objects of JLabel class.
JLabel l1, l2, l3, l4, l5;

// Constructor of Example class.


public Example()
{
// Creating Object of "FlowLayout" class
FlowLayout layout = new FlowLayout();

// this Keyword refers to current object.


// Function to set Layout of JFrame.
this.setLayout(layout);

// Initialization of object "l1" of JLabel class.


l1 = new JLabel("Label 1 ");

// Initialization of object "l2" of JLabel class.


l2 = new JLabel("Label 2 ");

// Initialization of object "l3" of JLabel class.


l3 = new JLabel("Label 3 ");

// Initialization of object "l4" of JLabel class.


l4 = new JLabel("Label 4 ");
// Initialization of object "l5" of JLabel class.
l5 = new JLabel("Label 5 ");

// this Keyword refers to current object.


// Adding Jlabel "l1" on JFrame.
this.add(l1);

// Adding Jlabel "l2" on JFrame.


this.add(l2);

// Adding Jlabel "l3" on JFrame.


this.add(l3);

// Adding Jlabel "l4" on JFrame.


this.add(l4);

// Adding Jlabel "l5" on JFrame.


this.add(l5);
}
}

class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();

// Function to set title of JFrame.


f.setTitle("Example of FlowLayout");

// Function to set Bounds of JFrame.


f.setBounds(200, 100, 600, 400);

// Function to set visible status of JFrame.


f.setVisible(true);
}
}
2. Output:

3. We can control the alignment of components in a


flow layout arrangement, by using these FlowLayout
Fields.
1) RIGHT :- Each row of component shifts towards right.
2) LEFT :- Each row of component shifts towards left.

4. Program 2: The following program illustrates the use of


FlowLayout using Right alignment by passing the
argument FlowLayout.RIGHT in the constructor of
FLowLayout. We create 5 JLabel components named “l1”,
“l2″… “l5” and then add them to the JFrame by the
method this.add(). We set the title and bounds of the
frame by method setTitle and setBounds.
The layout is set by the method setLayout();
// Java program to show example of
// FlowLayout and using RIGHT alignment
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Example extends JFrame {


// Declaration of objects of JLabel class.
JLabel l1, l2, l3, l4, l5;

// Constructor of Example class.


public Example()
{
// Creating Object of "FlowLayout" class, passing
// RIGHT alignment through constructor.
FlowLayout layout = new FlowLayout(FlowLayout.RIGHT);

// this Keyword refers to current object.


// Function to set Layout of JFrame.
this.setLayout(layout);

// Initialization of object "l1" of JLabel class.


l1 = new JLabel("Label 1 ");

// Initialization of object "l2" of JLabel class.


l2 = new JLabel("Label 2 ");

// Initialization of object "l3" of JLabel class.


l3 = new JLabel("Label 3 ");

// Initialization of object "l4" of JLabel class.


l4 = new JLabel("Label 4 ");

// Initialization of object "l5" of JLabel class.


l5 = new JLabel("Label 5 ");

// this Keyword refers to current object.


// Adding Jlabel "l1" on JFrame.
this.add(l1);

// Adding Jlabel "l2" on JFrame.


this.add(l2);

// Adding Jlabel "l3" on JFrame.


this.add(l3);

// Adding Jlabel "l4" on JFrame.


this.add(l4);

// Adding Jlabel "l5" on JFrame.


this.add(l5);
}
}

class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();

// Function to set title of JFrame.


f.setTitle("Example of FlowLayout");

// Function to set Bounds of JFrame.


f.setBounds(200, 100, 600, 400);

// Function to set visible status of JFrame.


f.setVisible(true);
}
}

5. Output:
Java AWT | BorderLayout Class
Last Updated : 06 Oct, 2021



BorderLayout is the default layout for the window objects such as
JFrame, JWindow, JDialog, JInternalFrame etc. BorderLayout
arranges the components in the five regions. Four sides are
referred to as north, south, east, and west. The middle part is
called the center. Each region can contain only one component
and is identified by a corresponding constant
as NORTH, SOUTH, EAST, WEST, and CENTER.
Constructors:
1. BorderLayout(): It will construct a new borderlayout
with no gaps between the components.
2. BorderLayout(int, int): It will constructs a border layout
with the specified gaps between the components.
Commonly Used Methods:
1. toString(): Returns a string which is the representation
of the state of border layout.
2. getLayoutAlignmentX(Container parent): Returns the
layout alignment along the X-axis.
3. getLayoutAlignmentY(Container parent): It will
return the layout alignment along the Y-axis.
4. removeLayoutComponent(Component comp): This
method is used to remove the specified component from
the borderlayout.
5. getVgap(): Return the vertical gap between the
components.
6. getHgap(): Returns the Horizontal gap between the
components.
7. setHgap(int hgap): It is used to set the horizontal gap
between the components.
8. setVgap(int vgap): It is used to set the vertical gap
between the components.
Below Programs will illustrate the BorderLayout class:
 Program 1: The following program creates JButton
components in a JFrame, whose instance class is
“BorderLayoutDemo”. We create 5 JButton and then add
them to the JFrame by using add() method. We will set
the size and visibility of the frame by
using setSize() and setVisible() method respectively. The
layout is set by using the setLayout() method.
 Java

// Java program to illustrate the BorderLayout


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// class extends JFrame


class BoderLayoutDemo extends JFrame {

BoderLayoutDemo()
{

// Creating Object of Jpanel class


JPanel pa = new JPanel();

// set the layout


pa.setLayout(new BorderLayout());

// add a new JButton with name "wel" and it is


// lie top of the container
pa.add(new JButton("WelCome"), BorderLayout.NORTH);

// add a new JButton with name "come" and it is


// lie button of the container
pa.add(new JButton("Geeks"), BorderLayout.SOUTH);

// add a new JButton with name "Layout" and it is


// lie left of the container
pa.add(new JButton("Layout"), BorderLayout.EAST);

// add a new JButton with name "Border" and it is


// lie right of the container
pa.add(new JButton("Border"), BorderLayout.WEST);

// add a new JButton with name "hello everybody" and it is


// lie center of the container
pa.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER);

// add the pa object which refer to the Jpanel


add(pa);

// Function to close the operation of JFrame.


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Function to set size of JFrame.
setSize(300, 300);

// Function to set visible status of JFrame.


setVisible(true);
}
}

class MainFrame {

// Driver code
public static void main(String[] args)
{

// calling the constructor


new BoderLayoutDemo();
}
}

Output:

 Program 2: This program will show how to pass the


arguments in BorderLayout. Set the background color by
using setBackground() method. We create 5 JButton
components named “btn1“, “btn2“, “btn3“, “btn4“,
“btn5“, and then add them to the JFrame by
using add() method. We set the title, size, and visibility of
the frame by
using setTitle(), setSize() and setVisible() methods
respectively. The layout is set by the method setLayout().
 Java

// Java program to illustrate the BorderLayout


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Button;
import java.awt.Color;

// class extends JFrame


public class BorderDemo extends JFrame {

// Constructor of BorderDemo class.


public BorderDemo()
{

// set the layout


setLayout(new BorderLayout());

// set the background


setBackground(Color.red);

// creates Button (btn1)


Button btn1 = new Button("Geeks");

// creates Button (btn2)


Button btn2 = new Button("GFG");

// creates Button (btn3)


Button btn3 = new Button("Sudo Placement");

// creates Button (btn4)


Button btn4 = new Button("GeeksforGeeks");

// creates Button (btn5)


Button btn5 = new Button("Java");

// Adding JButton "btn1" on JFrame.


add(btn1, "North");

// Adding JButton "btn2" on JFrame.


add(btn2, "South");

// Adding JButton "btn3" on JFrame.


add(btn3, "East");

// Adding JButton "btn4" on JFrame.


add(btn4, "West");

// Adding JButton "btn5" on JFrame.


add(btn5, "Center");

// function to set the title


setTitle("Learning a Border Layout");

// Function to set size of JFrame.


setSize(350, 300);

// Function to set visible status of JFrame


setVisible(true);
}

// Main Method
public static void main(String args[])
{

// calling the constructor


new BorderDemo();
}
}

Output:

Note: The above programs might not run in an online IDE. Please
use an offline compiler.
Java AWT | GridLayout Class
Last Updated : 21 Aug, 2018



GridLayout class represents a layout manager with a specified
number of rows and columns in a rectangular grid. The
GridLayout container is divided into an equal-sized of rectangles,
and one of the components is placed in each rectangle. Every
rectangle cell has the same size therefore, they contain a
component, which fills the entire cell. When the user changes or
adjusts the size of the container, the size of each rectangles
changes accordingly.
Constructors of the class:
1. GridLayout(): It Creates a grid layout with a default of
one column per component, in a single row.
2. GridLayout(int rw, int cl): It creates a grid layout with
the specified number of rows and columns.
3. GridLayout(int rw, int cl, int hgap, int vgap): It
creates a grid layout with the specified number of rows
and columns with horizontal and vertical gap.
Commonly Used Methods:
 addLayoutComponent(String str, Component
cmp): Adds the specified component with the specified
name to the layout.
 setColumns(int cl): Sets the number of columns in this
layout to the specified value.
 setHgap(int hgap): Sets the horizontal gap between
components to the specified value.
 setRows(int rw): Sets the number of rows in this layout
to the specified value.
 setVgap(int vgap): Sets the vertical gap between
components to the specified value.
 layoutContainer(Container pr): Lays out the specified
container using this layout.
 toString(): Returns the string representation of this grid
layout’s values.
Below programs illustrate the GridLayout class:
 Program 1: In below program we are passing the
argument in GridLayout. We create 4 JLabel components
named “one“, “two“, “three“, “four” and create
2 JButton components named “buttonsave” and
“buttonexit” and create 4 Jtextfield components named
“tname“, “tcode“, “tdesig“, “tsalary” and all of add them
to the JFrame by the method add(). We will set the
visibility and size of the frame by
using setVisible() and setSize() method. The layout is set
by using setLayout() method.
// Java program to illustrate the GridLayout
import javax.swing.*;
import java.awt.*;

// class GridLayout extends JFrame


public class GridLayoutDemo extends JFrame {

GridLayoutDemo() {

// Creating Object P1 of JPanel class


JPanel p1 = new JPanel();

// set the layout


p1.setLayout(new GridLayout(4, 2));

// Creating Object of "FlowLayout" class


FlowLayout layout = new FlowLayout();

// Creating Object P2 of JPanel class


JPanel p2 = new JPanel();

// set the layout


p2.setLayout(layout);

// Declaration of objects of JLabel class.


JLabel one, two, three, four;

// Declaration of objects of JTextField class.


JTextField tname, tsalary, tcode, tdesig;

// Declaration of objects of JButton class.


JButton buttonSave, buttonExit;
// Initialization of object
// "one" of JLabel class.
one = new JLabel("NAME");

// Initialization of object
// "tname" of JTextField class.
tname = new JTextField(20);

// Initialization of object
// "two" of JLabel class.
two = new JLabel("CODE");

// Initialization of object
// "tcode" of JTextField class.
tcode = new JTextField(20);

// Initialization of object
// "three" of JLabel class.
three = new JLabel("DESIGNATION");

// Initialization of object
// "tdesig" of JTextField class.
tdesig = new JTextField(20);

// Initialization of object
// "four" of JLabel class.
four = new JLabel("SALARY");

// Initialization of object
// "tsalary" of JTextField class.
tsalary = new JTextField(20);

// Initialization of object
// "buttonsave" of JButton class.
buttonSave = new JButton("SAVE");

// Initialization of object
// "buttonexit" of JButton class.
buttonExit = new JButton("EXIT");

// Adding Jlabel "one" on JFrame.


p1.add(one);

// Adding JTextField "tname" on JFrame.


p1.add(tname);
// Adding Jlabel "two" on JFrame.
p1.add(two);

// Adding JTextField "tcode" on JFrame.


p1.add(tcode);

// Adding Jlabel "three" on JFrame.


p1.add(three);

// Adding JTextField "tdesig" on JFrame.


p1.add(tdesig);

// Adding Jlabel "four" on JFrame.


p1.add(four);

// Adding JTextField "tsalary" on JFrame.


p1.add(tsalary);

// Adding JButton "buttonsave" on JFrame.


p2.add(buttonSave);

// Adding JButton "buttonexit" on JFrame.


p2.add(buttonExit);

// add the p1 object which


// refer to the Jpanel
add(p1, "North");

// add the p2 object which


// refer to the Jpanel
add(p2, "South");

// Function to set visible


// status of JFrame.
setVisible(true);

// this Keyword refers to current


// object. Function to set size of JFrame.
this.setSize(400, 180);
}

// Main Method
public static void main(String args[])
{
// calling the constructor
new GridLayoutDemo();
}
}

 Output:
 Video Player
 00:00
 00:22

 Program 2: In below program we are passing the


argument in GridLayout. We create 5 JButton components
named “btn1“, “btn2“, “btn3“, “btn4“, “btn5” and then
add them to the JFrame by the method add(). We will set
the visibility and size of the frame by
using setvisible() and setsize() method. The layout is set
by using setLayout() method.
// Java program to illustrate the GridLayout
import java.awt.*;
import javax.swing.*;

// create a class griddemo


public class Griddemo {

// Main Method
public static void main(String[] args)
{

// Creating Object of JFrame class


// with new name frame
JFrame frame = new JFrame("GridLayout Demo");

// Initialization of object
// "btn1" of JButton class.
JButton btn1 = new JButton("Button 1");

// Initialization of object
// "btn2" of JButton class.
JButton btn2 = new JButton("Button 2");

// Initialization of object
// "btn3" of JButton class.
JButton btn3 = new JButton("Button 3");

// Initialization of object
// "btn4" of JButton class.
JButton btn4 = new JButton("Button 4");

// Initialization of object
// "btn5" of JButton class.
JButton btn5 = new JButton("Button 5");

// Creating Object Panel of JPanel class


// create grid layout with 3 rows,
// 2 columns with horizontal and
// vertical gap set to 10
JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));

// Adding JButton "btn1" on JPanel.


panel.add(btn1);

// Adding JButton "btn2" on JPanel.


panel.add(btn2);

// Adding JButton "btn3" on JPanel.


panel.add(btn3);

// Adding JButton "btn4" on JPanel.


panel.add(btn4);

// Adding JButton "btn5" on JPanel.


panel.add(btn5);

// Function to close the operation of JFrame.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Function to set size of JFrame.


frame.setSize(300, 150);

// Function to get the content of JFrame.


frame.getContentPane().add(panel);

// Function to set visible status of JFrame.


frame.setVisible(true);
}
}

 Output:
 Video Player
 00:00
 00:16
Note: The above programs might not run in an online IDE. Please
use an offline compiler.

Java AWT | BorderLayout Class


Last Updated : 06 Oct, 2021



BorderLayout is the default layout for the window objects such as
JFrame, JWindow, JDialog, JInternalFrame etc. BorderLayout
arranges the components in the five regions. Four sides are
referred to as north, south, east, and west. The middle part is
called the center. Each region can contain only one component
and is identified by a corresponding constant
as NORTH, SOUTH, EAST, WEST, and CENTER.
Constructors:
1. BorderLayout(): It will construct a new borderlayout
with no gaps between the components.
2. BorderLayout(int, int): It will constructs a border layout
with the specified gaps between the components.
Commonly Used Methods:
1. toString(): Returns a string which is the representation
of the state of border layout.
2. getLayoutAlignmentX(Container parent): Returns the
layout alignment along the X-axis.
3. getLayoutAlignmentY(Container parent): It will
return the layout alignment along the Y-axis.
4. removeLayoutComponent(Component comp): This
method is used to remove the specified component from
the borderlayout.
5. getVgap(): Return the vertical gap between the
components.
6. getHgap(): Returns the Horizontal gap between the
components.
7. setHgap(int hgap): It is used to set the horizontal gap
between the components.
8. setVgap(int vgap): It is used to set the vertical gap
between the components.
Below Programs will illustrate the BorderLayout class:
 Program 1: The following program creates JButton
components in a JFrame, whose instance class is
“BorderLayoutDemo”. We create 5 JButton and then add
them to the JFrame by using add() method. We will set
the size and visibility of the frame by
using setSize() and setVisible() method respectively. The
layout is set by using the setLayout() method.
 Java

// Java program to illustrate the BorderLayout


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// class extends JFrame


class BoderLayoutDemo extends JFrame {

BoderLayoutDemo()
{

// Creating Object of Jpanel class


JPanel pa = new JPanel();

// set the layout


pa.setLayout(new BorderLayout());

// add a new JButton with name "wel" and it is


// lie top of the container
pa.add(new JButton("WelCome"), BorderLayout.NORTH);

// add a new JButton with name "come" and it is


// lie button of the container
pa.add(new JButton("Geeks"), BorderLayout.SOUTH);

// add a new JButton with name "Layout" and it is


// lie left of the container
pa.add(new JButton("Layout"), BorderLayout.EAST);
// add a new JButton with name "Border" and it is
// lie right of the container
pa.add(new JButton("Border"), BorderLayout.WEST);

// add a new JButton with name "hello everybody" and it is


// lie center of the container
pa.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER);

// add the pa object which refer to the Jpanel


add(pa);

// Function to close the operation of JFrame.


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Function to set size of JFrame.


setSize(300, 300);

// Function to set visible status of JFrame.


setVisible(true);
}
}

class MainFrame {

// Driver code
public static void main(String[] args)
{

// calling the constructor


new BoderLayoutDemo();
}
}

Output:
 Program 2: This program will show how to pass the
arguments in BorderLayout. Set the background color by
using setBackground() method. We create 5 JButton
components named “btn1“, “btn2“, “btn3“, “btn4“,
“btn5“, and then add them to the JFrame by
using add() method. We set the title, size, and visibility of
the frame by
using setTitle(), setSize() and setVisible() methods
respectively. The layout is set by the method setLayout().
 Java

// Java program to illustrate the BorderLayout


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Button;
import java.awt.Color;

// class extends JFrame


public class BorderDemo extends JFrame {

// Constructor of BorderDemo class.


public BorderDemo()
{

// set the layout


setLayout(new BorderLayout());
// set the background
setBackground(Color.red);

// creates Button (btn1)


Button btn1 = new Button("Geeks");

// creates Button (btn2)


Button btn2 = new Button("GFG");

// creates Button (btn3)


Button btn3 = new Button("Sudo Placement");

// creates Button (btn4)


Button btn4 = new Button("GeeksforGeeks");

// creates Button (btn5)


Button btn5 = new Button("Java");

// Adding JButton "btn1" on JFrame.


add(btn1, "North");

// Adding JButton "btn2" on JFrame.


add(btn2, "South");

// Adding JButton "btn3" on JFrame.


add(btn3, "East");

// Adding JButton "btn4" on JFrame.


add(btn4, "West");

// Adding JButton "btn5" on JFrame.


add(btn5, "Center");

// function to set the title


setTitle("Learning a Border Layout");

// Function to set size of JFrame.


setSize(350, 300);

// Function to set visible status of JFrame


setVisible(true);
}

// Main Method
public static void main(String args[])
{

// calling the constructor


new BorderDemo();
}
}

Output:

Note: The above programs might not run in an online IDE. Please
use an offline compiler.

GUI Full Form


Last Updated : 01 Sep, 2023



GUI is a user-friendly interface used to communicate with the help
of electronic devices. It displays all the contents whether a text
file or an object or pictures or videos and all the things that a user
wants to visualize.
What is the full form of GUI?
GUI stands for Graphical User Interface. GUI interacts well and can
be used everywhere whether a mobile phone, tablet, laptop,
personal computer, and all the other electronic devices. It can be
used best on the gaming side where the resolution is being
considered. The basic GUI format is represented in the form of the
diagram:

GUI components
All the important GUI components are listed below
Pointer
Pops up in the screen and proceeds to select objects.
Pointing tool
Picking up of objects is done by pointing tool, for example
– Trackball, Mouse.
Icons
Refers to small images on the screen which represent
commands, documents, and windows.
Desktop
The screen that is contains the icons.
History of GUI
Earlier, there was no GUI so people used to interact with
the command-line interface(CLI). The CLI was not that friendly to
use and the end-user was not familiar with all the commands. So
to bridge this gap, GUI was introduced. The main aim of the GUI
was to make the applications much more user-friendly. People
love when the task which they want to perform gets done easily
and in an efficient manner. GUI stresses one of the most
important aspects which is ease of use. The basic structure of GUI
using implied authority is given in the following diagram

How Does GUI Works


Windows, icons, and menus are used by a GUI to execute
operations including opening, deleting, and moving files. Although
a mouse is typically used to browse a GUI operating system, a
keyboard can also be used by employing keyboard shortcuts or
the arrow keys.
On a GUI system, for instance, you would move the mouse pointer
to the program’s icon and double-click it to open the program. To
go to the directory holding the program, list the files, and then
launch the file using a command line interface, you must be
familiar with the commands.
GUI Examples
Ivan Sutherland at MIT created Sketchpad in 1962, which is
thought to be the first graphic computer-aided design application.
It featured a light pen that allowed users to create and alter
things in engineering drawings in real time with coordinated
graphics.
Virtually every interactive application, including ATMs, self-service
checkouts, airline self-ticketing and check-in, video games,
smartphones, and desktops, incorporates modern operating
systems and graphical user interfaces. For desktop environments,
examples of well-liked contemporary graphical user interfaces
include Microsoft Windows, macOS, Ubuntu Unity, and GNOME
Shell; for mobile platforms, examples include Android, Apple’s
iOS, BlackBerry OS, Palm OS-WebOS, Windows 10 Mobile, and
Firefox OS.
Benefits of GUI
 As mentioned above they are user-friendly i.e. very easy
to use.
 A GUI consists of different characteristics such as a Menu,
Tabs, Pointers, and many more kinds of stuff.
 The icons represent on the user interface represent
the software or the file or some application required on
the screen.
 Graphical User Interface is pretty simple and convenient
for beginners to understand.
 It is very intuitive and user-friendly and can be used by
anyone.
 End-user need not memorize commands to perform
actions in the application.
Limitations of GUI
 A bad GUI always create a problem for gamers as it
creates a bad impact on them
 A GUI that is not user-friendly can mislead the user and
the efficiency of completing the work reduces.
Java AWT Button
Last Updated : 26 Nov, 2023



Abstract Window Toolkit, also known as AWT is a library for
creating Graphical User Interfaces (GUIs) in Java applications.
Within the Java AWT library, you’ll find a collection of classes and
methods designed to develop windows and essential user
interface elements. The Button class is a control component in
AWT, that triggers an event when it is clicked.
Button in Java AWT
The ‘Button’ class is a part of the ‘java.awt’ package which has a
collection of classes and methods for creating GUI components.
Java AWT Buttons can be used to perform several actions like
saving a file, closing a window, submitting a form, or triggering
any specific action.
When we press a button, AWT creates an instance
of ActionEvent and delivers it by calling processEvent on the
button. The processEvent method of the button accepts all
events and then sends an action event to its own
function processActionEvent. The ActionListener interface
must be implemented if one wants to execute an action when a
button is pressed.
Syntax of Java AWT Button
public class Button extends Component implements Accessible
Constructors of Button
There are 2 types of Constructors in the AWT Button class.
 Button(): Creates a new button with the label as an
empty string.
 Button(String label): Creates a new button with the
label as the specified string as a parameter.
Java AWT Button Class methods
List of all the methods associated with the AWT button and its
Description
Method Description

void addActionListener(ActionListener The action listener is added to receive


Method Description

l) action events from this button.

void addNotify() Creates the peer of the button.

The method returns


AccessibleContext
the AccessibleContext associated with
getAccessibleContext()
this Button.

The method returns the command name


String getActionCommand() of the action event triggered by this
button.

The method returns an array of all the


ActionListener[] getActionListeners() action listeners that have been
registered on this button.

String getLabel() Retrieves the label of this button.

The method returns an array of all the


<T extends EventListener> T[]
objects that are currently registered as
getListeners(Class<T> listenerType)
FooListeners on this Button.

Returns a string that represents the


protected String paramString()
status of this Button.

Sends action events to any registered


protected void ActionListener objects in order to
processActionEvent(ActionEvent e) process them when they occur on this
button.

protected void processEvent(AWTEvent


Processes events on this button.
e)

void The specified action listener is removed


removeActionListener(ActionListener l) from the button.

void setActionCommand(String Configures the action event by setting


command) the command name.
Method Description

Sets the button’s label to be the


void setLabel(String label)
specified string.

Inherited Methods
The Methods included with AWT button are inherited by:
 java.awt.Component
 java.lang.Object
Examples of Java AWT Button
Let us understand the AWT Button class and their methods with
some examples given below:
Example 1 (Basic Button):
The example given below is a simple implementation of a Button
with a label.
 Java

// Java AWT Program to create


// Basic Button
import java.awt.Button;
import java.awt.Frame;

// Driver Class
public class Main {
// main function
public static void main(String[] args)
{
// Create a frame
Frame frame = new Frame("AWT Button Example");
// Create a button
Button button = new Button("Click Me!");

// Set the button position on the frame


button.setBounds(150, 130, 100, 30);

// Add the button to the frame


frame.add(button);

// Set the frame size and layout


frame.setSize(400, 300);
frame.setLayout(null);

// Set the frame visibility to true


frame.setVisible(true);
}
}

Run the code using the following commands:


javac Main.java
java Main

Output:

Final Output Created:

Example 2 (Adding Multiple Properties):


In the below example, there are multiple buttons each having
different properties and attributes.
 Java

// Java AWT Program for


// Adding Multiple Properties
import java.awt.*;
import java.awt.Font;

// Driver Class
public class Main {
// main function
public static void main(String[] args){

// Create a frame
Frame frame = new Frame("AWT Button Example");

// Button 1
Button button1 = new Button("Click Me!");

// Set the background color


button1.setBackground(Color.BLUE);

// Set the foreground color


button1.setForeground(Color.WHITE);

// Set the button font size


button1.setFont(new Font("Arial", Font.BOLD, 14));

// Set the button position


button1.setBounds(150, 50, 100, 50);

// Button 2 with different properties


Button button2 = new Button("Press Me!");
button2.setBackground(Color.GREEN);
button2.setForeground(Color.BLACK);

button2.setFont(new Font("Times New Roman", Font.PLAIN,


16));
button2.setBounds(150, 140, 80, 30);

// Button 3 with different properties


Button button3 = new Button("Tap Me!");
button3.setBackground(Color.RED);
button3.setForeground(Color.WHITE);

button3.setFont(new Font("Verdana", Font.ITALIC, 16));


button3.setBounds(130, 220, 150, 80);

// Add the buttons to the frame


frame.add(button1);
frame.add(button2);
frame.add(button3);

// Set the frame background color


frame.setBackground(Color.LIGHT_GRAY);

// Set the frame size and make it visible


frame.setSize(400, 400);
frame.setLayout(null);

// Set the frame visibility to true


frame.setVisible(true);
}
}

Output:

Final Output Created:


Example 3 (ActionListener):
In this example, an ActionListener is called when the button is
clicked. It triggers an event and the label is displayed on the
screen.
 Java

// Java AWT Program to demonstrate


// Button with ActionListener
import java.awt.*;
import java.awt.event.*;

// Driver Class
public class Main {
// main function
public static void main(String[] args)
{
// Create a frame
Frame frame = new Frame("AWT Button Example");

// Create a button
Button b = new Button("Click Here!");

// Set the position of the button


b.setBounds(160, 80, 80, 40);

// Add a background color


b.setBackground(Color.GREEN);

// Create a label
Label label = new Label();
// Set the position of the label
label.setBounds(80, 140, 280, 20);

// Set the properties of the label


label.setForeground(Color.BLUE);
label.setFont(new Font("Arial", Font.BOLD, 14));

// Add an action listener to the button


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
label.setText(
"Hey geek, Welcome to GeeksforGeeks!!");
}
});

// Add button to the frame


frame.add(b);

// Add Label to the frame


frame.add(label);

// Add background color to the frame


frame.setBackground(Color.LIGHT_GRAY);

// Set the size, layout and visibility


frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}

Output:
Final Output Created:

You might also like