Event Handling in Java
An event can be defined as changing the state of an object or behaviour by
performing actions. Actions can be a button click, cursor movement, key press
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
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 and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
java.awt.event package provides many event classes and Listener interfaces for event handlin
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the component it may be
button, textfield etc.
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField, ChechBox,
button, etc.
For example, an AWT GUI with components like TextField, label and button
will have different look and feel for the different platforms like Windows, MAC
OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates
those components.
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we
can add a container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
public void setVisible(boolean status) Changes the visibility of the component, by
default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to
create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
// importing Java AWT class
import java.awt.*;
// extending Frame class to our class AWTExample1
public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the
above example that sets the position of the awt button.
Output:
Java AWT Button
A button is basically a control component with a label that generates an event
when pushed. The Button class is used to create a labeled button that has
platform independent implementation. The application result in some action
when the button is pushed.
When we press a button and release it, AWT sends an instance
of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then it
passes an action event by calling its own method processActionEvent. This
method passes the action event on to action listeners that are interested in the
action events generated by the button.
To perform an action on a button being pressed and released,
the ActionListener interface needs to be implemented. The registered new
listener can receive events from the button by
calling addActionListener method of the button. The Java application can use
the button's action command as a messaging protocol.
AWT Button Class Declaration
1. public class Button extends Component implements Accessible
Button Class Constructors
Following table shows the types of Button class constructors
Sr. Constructor Description
no.
1. Button( ) It constructs a new button with an empty string i.e. it
has no label.
2. Button (String It constructs a new button with given string as its
text) label.
ButtonExample.java
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// initializing the labels
l1 = new Label ("CSEA.");
l2 = new Label ("CSEB.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
To compile the program using command prompt type the following commands
1. C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
If there's no error, we can execute the code using:
1. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.
AWT Label Class Declaration
public class Label extends Component implements Accessible
public class LabelExample {
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("SECOND YEARS");
Label l1, l2;
// initializing the labels
l1 = new Label ("CSEA.");
l2 = new Label ("CSEB.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
Sr. Method name Description
no.
1. void addAdjustmentListener It adds the given adjustment listener to
(AdjustmentListener l) receive instances of AdjustmentEvent from
the scroll bar.
2. void addNotify() It creates the peer of scroll bar.
3. int getBlockIncrement() It gets the block increment of the scroll bar.
4. int getMaximum() It gets the maximum value of the scroll bar.
5. int getMinimum() It gets the minimum value of the scroll bar.
// importing awt package
import java.awt.*;
public class ScrollbarExample1 {
// class constructor
ScrollbarExample1() {
// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();
// setting the position of scroll bar
s.setBounds (100, 100, 50, 100);
// adding scroll bar to the frame
f.add(s);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[]) {
new ScrollbarExample1();
}
}
Output:
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the
text area becomes larger than the viewable area, the scroll bar appears
automatically which helps us to scroll the text up and down, or right and left.
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:
o static int SCROLLBARS_BOTH - It creates and displays both
horizontal and vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and
displays only the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays
only the vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any
scrollbar in the text area.
Sr. Method name Description
no.
1 void append(String str) It appends the specified text to the current text of
text area.
2 int getColumns() It returns the number of columns of text area.
3 int getRows() It returns the number of rows of text area.
4 void insert(String str, int It inserts the specified text at the specified position
pos) in this text area.
5 void setColumns(int It sets the number of columns for this text area.
columns)
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample2 extends Frame implements ActionListener
{
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
TextAreaExample2() {
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
// adding ActionListener to button
b.addActionListener(this);
// adding components to frame
add(l1);
add(l2);
add(area);
add(b);
// setting the size, layout and visibility of frame
setSize(400, 450);
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
// main method
public static void main(String[] args) {
new TextAreaExample2();
}
}
Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox.
At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off"
or from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable, Acces
sible
Java AWT Checkbox Example with ItemListener
In the following example, we have created two checkboxes and adding them
into the Frame. Here, we are adding the ItemListener with the checkbox which
displays the state of the checkbox (whether it is checked or unchecked) using
the getStateChange() method.
CheckboxExample2.java
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
CheckboxExample2() {
Frame f = new Frame ("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
f.add(che
ckbox1);
f.add(checkbox2);
f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"uncheck
ed") } });
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CheckboxExample2();
}
}
Output:
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits
the Component class.
Class methods
Sr. Method name Description
no.
1. void addNotify() It creates the canvas's peer.
2. void createBufferStrategy (int It creates a new multi buffering
numBuffers) strategies on the particular component.
3. void createBufferStrategy (int It creates a new multi buffering
numBuffers, BufferCapabilities strategies on the particular component
caps) with the given buffer capabilities.
4. AccessibleContext It gets the accessible context related to
getAccessibleContext() the Canvas.
5. BufferStrategy getBufferStrategy() It returns the buffer strategy used by
the particular component.
6. void paint(Graphics g) It paints the canvas with given
Graphics object.
7. void pdate(Graphics g) It updates the canvas with given
Graphics object.
// importing awt class
import java.awt.*;
// class to construct a frame and containing main method
public class CanvasExample
{
// class constructor
public CanvasExample()
{
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
ss f.add(new MyCanvas());
// setting layout, size and visibility of frame
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CanvasExample();
}
}
// class which inherits the Canvas class
// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
// paint() method to draw inside the canvas
public void paint(Graphics g)
{
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Output:
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Acces
sible
Java AWT Choice Example with ActionListener
In the following example, we are creating a choice menu with 5 items. Along
with that we are creating a button and a label. Here, we are adding an event to
the button component using addActionListener(ActionListener a) method i.e.
the selected item from the choice menu is displayed on the label when the
button is clicked.
ExampleChoice.java
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class ExampleChoice{
ExampleChoice( ) {
Frame f = new Frame( );
final Label label = new Label( );
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
Button b = new Button("Show");
b.setBounds(200, 100, 50, 20);
final Choice c = new Choice( );
c.setBounds(100, 100, 75, 75);
c.add("CSEA");
c.add("CSEB");
c.add("AIML");
c.add("DS");
c.add("SECSIOT");
// adding above components into the frame
f.add(c);
f.add(label);
f.add(b);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// adding event to the button
// which displays the selected item from the list when button is clicked
b.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
String data = "Select Branch of Second
years: "+ c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
// main method
public static void main(String args[])
{
new ExampleChoice( );
}
}
Output:
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible
Java AWT List Example with ActionListener
In the following example, we are creating two List components, a Button and a
Label and adding them into the frame. Here, we are generating an event on the
button using the addActionListener(ActionListener l) method. On clicking the
button, it displays the selected programming language and the framework.
ListExample2.java
// importing awt and event class
import java.awt.*;
import java.awt.event.*;
public class ListExample2
{
// class constructor
ListExample2() {
// creating the frame
Frame f = new Frame();
// creating the label which is final
final Label label = new Label();
// setting alignment and size of label
label.setAlignment(Label.CENTER);
label.setSize(500, 100);
// creating a button
Button b = new Button("Show");
// setting location of button
b.setBounds(200, 150, 80, 30);
// creating the 2 list objects of 4 rows
// adding items to the list using add()
// setting location of list components
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
l1.add("CSE");
l1.add("AIML");
l1.add("DS");
l1.add("SECSIOT");
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("SECTION A");
l2.add("SECTION B");
// adding List, Label and Button to the frame
f.add(l1);
f.add(l2);
f.add(label);
f.add(b);
// setting size, layout and visibility of frame
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
// generating event on the button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Branch Selected of Second
years : "+l1.getItem(l1.getSelectedIndex());
data += ", Section Selected :";
for(String frame:l2.getSelectedItems()) {
data += frame + " ";
}
label.setText(data);
}
});
}
// main method
public static void main(String args[])
{
new ListExample2();
}
}
Output:
Java AWT Panel
The Panel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
public class Panel extends Container implements Accessible
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.
AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If
you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.
The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below.
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes
Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are the following
classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center. Each region (area) may contain one component
only. It is the default layout of a frame or window. The BorderLayout provides
five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as N
ORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SO
UTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAS
T
JButton b4 = new JButton("WEST");; // the button will be labeled as WES
T
JButton b5 = new JButton("CENTER");; // the button will be labeled as C
ENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Directi
on
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Directi
on
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Directio
n
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a
row.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns along with given horizontal and
vertical gaps.
// import statements
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
// setting the grid layout using the parameterless constructor
frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.
// import statements
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
{
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b
4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(
b8);
frameObj.add(b9); frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
Java CardLayout
The Java CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a card that
is why it is known as CardLayout.
Constructors of CardLayout Class
1. CardLayout(): creates a card layout with zero horizontal and vertical
gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Commonly Used Methods of CardLayout Class
o public void next(Container parent): is used to flip to the next card of
the given container.
o public void previous(Container parent): is used to flip to the previous
card of the given container.
o public void first(Container parent): is used to flip to the first card of
the given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Example of CardLayout Class: Using Default Constructor
The following program uses the next() method to move to the next card of the
container.
FileName: CardLayoutExample1.java
// import statements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample1 extends JFrame implements ActionListe
ner
{
CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
Container cPane;
// constructor of the class
CardLayoutExample1()
{
cPane = getContentPane();
//default constructor used
// therefore, components will
// cover the whole area
crd = new CardLayout();
cPane.setLayout(crd);
// creating the buttons
btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
cPane.add("a", btn1); // first card is the button btn1
cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3
}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon click
ing
crd.next(cPane);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();
// size is 300 * 300
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
The components may not be of the same size. Each GridBagLayout object
maintains a dynamic, rectangular grid of cells. Each component occupies one or
more cells known as its display area. Each component associates an instance of
GridBagConstraints.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridsy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Output:
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-
generic. Now generics force the java programmer to store a specific type of
objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
Type-safety: We can hold only a single type of objects in generics. It
doesn?t allow to store other objects.
Without Generics, we can store any type of objects.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not
occur at runtime. The good programming strategy says it is far better to handle
the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterface<Type>
Example to use Generics in java
ArrayList<String>
Full Example of Generics in Java
Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
element is: jai
rahul
jai
Example of Java Generics using Map
Now we are going to use map elements using generics. Here, we need to pass
key and value. Let us understand it by a simple example:
import java.util.*;
class TestGenerics2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"vijay");
map.put(4,"umesh");
map.put(2,"ankit");
//Now use Map.Entry for Set and Iterator
Set<Map.Entry<Integer,String>> set=map.entrySet();
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
while(itr.hasNext()){
Map.Entry e=itr.next();//no need to typecast
System.out.println(e.getKey()+" "+e.getValue());
}
}}
Output
1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as a generic class. Here, we are using
the T type parameter to create the generic class of specific type.
Let's see a simple example to create and use the generic class.
Creating a generic class:
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, and
Employee). The type you specify for the class will be used to store and retrieve
the data.
Using generic class:
Let's see the code to use the generic class.
class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}
Output
Type Parameters
The type parameters naming conventions are important to learn generics
thoroughly. The common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is
declared. It allows static as well as non-static methods.
Let's see a simple example of java generic method to print array elements. We are
using here E to denote the element.
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Output
Printing Integer Array
10
20
30
40
50
Printing Character Array
J
A
V
A