0% found this document useful (0 votes)
79 views85 pages

Unit 5 Notes

The document discusses various Java layout managers and event handling. It provides details on the BorderLayout, GridLayout, FlowLayout, CardLayout, and GridBagLayout classes. It explains how each layout positions components and includes code examples. It also covers the key components of event handling in Java - events, event sources, and listeners. It lists some important event classes and the listener interfaces they correspond to.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views85 pages

Unit 5 Notes

The document discusses various Java layout managers and event handling. It provides details on the BorderLayout, GridLayout, FlowLayout, CardLayout, and GridBagLayout classes. It explains how each layout positions components and includes code examples. It also covers the key components of event handling in Java - events, event sources, and listeners. It lists some important event classes and the listener interfaces they correspond to.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

UNIT-5

BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in
a particular manner. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are
following classes that represents the layout managers:
• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• javax.swing.BoxLayout
• javax.swing.GroupLayout
• javax.swing.ScrollPaneLayout
• javax.swing.SpringLayout etc.
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
frame or window. The BorderLayout provides five
constants for each region:

• public static final int NORTH


• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER
EXAMPLE:
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
} }
OUTPUT:
Java GridLayout
• The GridLayout is used to arrange the components in
rectangular grid. One component is displayed in each
rectangle.
• Constructors of GridLayout class
GridLayout(): creates a grid layout with one
column per component in a row.
GridLayout(int rows, int columns): creates a grid
layout with the given rows and columns but no gaps
between the components.
GridLayout(int rows, int columns, int hgap, int
vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps.
import java.awt.*;
import javax.swing.*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

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");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
} }
Java FlowLayout
The FlowLayout is used to arrange the
components in a line, one after another (in a
flow). It is the default layout of applet or
panel.
• Fields of FlowLayout class
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
Constructors of FlowLayout class
• FlowLayout(): creates a flow layout with
centered alignment and a default 5 unit
horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout
with the given alignment and a default 5 unit
horizontal and vertical gap.
• FlowLayout(int align, int hgap, int vgap):
creates a flow layout with the given alignment
and the given horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
JFrame f;
MyFlowLayout()
{
f=new JFrame();
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");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
} }
Java CardLayout
The 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
 CardLayout(): creates a card layout with zero
horizontal and vertical gap.
 CardLayout(int hgap, int vgap): creates a card
layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class
• public void next(Container parent): is used to
flip to the next card of the given container.
• public void previous(Container parent): is
used to flip to the previous card of the given
container.
• public void first(Container parent): is used to
flip to the first card of the given container.
• public void last(Container parent): is used to
flip to the last card of the given container.
• public void show(Container parent, String
name): is used to flip to the specified card
with the given name.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends Jframe
implements ActionListener
{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
{
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 3
0 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add(b1);
c.add(b2);
c.add(b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args)
{
CardLayoutExample cl=new CardLayoutExample()
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
} }
Java GridBagLayout

The Java GridBagLayout class is used to align components


vertically, horizontally or along their baseline.
• The components may not be of 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. With the
help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages
each component's minimum and preferred sizes in
order to determine component's size.
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 GridBagLayoutExa
mple();
}
public GridBagLayoutExample()
{
GridBagLayout grid = 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.gridy = 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);
}
}
UNIT-5
Event Handling
Java GUI Event Handling
Any program that uses GUI (graphical user interface) such
as Java application written for windows, is event driven.
Event describes the change in state of any object.

For Example :
 Pressing a button
 Entering a character in Textbox
 Clicking or Dragging a mouse, etc.
Components of Event Handling
Event handling has three main components,

 Events : An event is a change in state of


an object.

 Events Source : Event source is an


object that generates an event.

 Listeners : A listener is an object that


listens to the event. A listener gets
notified when an event occurs.
How Events are handled?
A source generates an Event and send it to one
or more listeners registered with the source.

 Once event is received by the listener, they


process the event and then return.

Events are supported by a number of Java


packages, like
java.util, java.awt and
java.awt.event.
Important Event Classes and Interface
Event Classes Description Listener Interface
ActionEvent generated when button is ActionListener
pressed, menu-item is selected,
list-item is double clicked
MouseEvent generated when mouse is MouseListener
dragged, moved,clicked,pressed
or released and also when it
enters or exit a component
KeyEvent generated when input is KeyListener
received from keyboard
ItemEvent generated when check-box or list ItemListener
item is clicked
TextEvent generated when value of TextListener
textarea or textfield is changed
import java.applet.*;
import java.awt.*;

public class event extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
/*<applet code="Test" width=300, height=100>
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.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
Java MouseAdapter Example

import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}

public static void main(String[] args)


{
new MouseAdapterExample();
}
}
Inner classes
 An inner class is a class which is defined inside another class.
The inner class can access all the members of an outer class, but
vice-versa is not true.

 The mouse event handling program which was simplified using


adapter classes can further be simplified using inner classes.

import java.awt.*;
import java.awt.event.*;
public class MyApplet extends JApplet
{
JLabel label;
public void init()
{
setSize(600,300);
setLayout(new FlowLayout());
label = new JLabel();
add(label);
addMouseListener(new MyAdapter());
}
class MyAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
label.setText("Mouse is clicked");
}
}
}
Anonymous Inner Classes

Anonymous inner classes are nameless inner classes


which can be declared inside another class or as an
expression inside a method definition.
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends JApplet
{
JLabel label;
public void init()
{
setSize(600,300);
setLayout(new FlowLayout());
label = new JLabel();
add(label);
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
label.setText("Mouse is clicked");
}
}
);
}
}
UNIT-5
Java Applet
Java Applet
• Applet is a special type of program that is embedded in
the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many
platforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked
only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool

import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
}
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
Parameter in Applet
• We can get any information from the HTML file as a
parameter. For this purpose, Applet class provides a
method named getParameter().
Syntax:
public String getParameter(String parameterName)
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}

/*
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
*/
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class JAppletDemo extends JApplet implements
ActionListener
{
JButton b;
JTextField t;
public void init()
{
t=new JTextField();
t.setBounds(30,40,220,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);
add(t);
b.addActionListener(this);
setLayout(null);
public void actionPerformed(ActionEvent e)
{
t.setText("Welcome to MRCE");
}
}

/*<applet code="JAppletDemo.class" width="300" height="300">


</applet>*/
Painting in Swing
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas
{

public void paint(Graphics g)


{
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);

}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}

}
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("Enter your name");
l1.setBounds(50,50, 100,30);
JTextField tf =new JTextField();
tf.setBounds(50,100, 150,20);
f.add(l1); f.add(tf);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
UNIT-5
The Swing Buttons
The Swing Buttons
 JButton,
 JToggle Button,
 JCheck Box,
 JRadio Button,
 JTabbed Pane,
 JScroll Pane,
 JList,
 JCombo Box,
 Swing Menus,
 Dialogs.
Java JButton
• The JButton class is used to create a labeled button. The
application result in some action when the button is
pushed. It inherits AbstractButton class.
JButton class declaration
 javax.swing.JButton class.
 public class JButton extends AbstractButton implem
ents Accessible
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JCheckBox
• The JCheckBox 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 ".It inherits JToggleButton class.
JCheckBox class declaration
 javax.swing.JCheckBox
 public class JCheckBox extends JToggleButton implement
s Accessible
Constructor Description

JJCheckBox() Creates an initially unselected


check box button with no text, no
icon.
JChechBox(String s) Creates an initially unselected
check box with text.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Java JRadioButton
The JRadioButton class is used to create a radio
button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz.

JRadioButton class declaration


javax.swing.JRadioButton

public class JRadioButton extends JToggleButton


implements Accessible
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Java JComboBox
• 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 JComponent class.
JComboBox class declaration
 javax.swing.JComboBox

Constructor Description

JComboBox() Creates a JComboBox with a


default data model.
JComboBox(Object[] items) Creates a JComboBox that
contains the elements in the
specified array.
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealan
d"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Java JList
• The object of JList class represents a list of text
items. The list of text items can be set up so
that the user can choose either one item or
multiple items. It inherits JComponent class.

Constructor Description

JList() Creates a JList with an empty,


read-only, model.
JList(ary[] listData) Creates a JList that displays the
elements in the specified array.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();

l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
Java JScrollBar
• The object of JScrollbar class is used to add
horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits
JComponent class.

Constructor Description

JScrollBar() Creates a vertical scrollbar with the


initial values.
JScrollBar(int orientation) Creates a scrollbar with the
specified orientation and the initial
values.
import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}

You might also like