MODULE-IV Complete Notes Java Events Handling Functions and LayoutManager-1
MODULE-IV Complete Notes Java Events Handling Functions and LayoutManager-1
PART-A
Java Events Handling Methods or Functions
Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
This mechanism have the code which is known as event handler that is
executed when an event occurs.
Java Uses the Delegation Event Model to handle the events.
Changing the state of an object is known as an event.
Example,: click on button, dragging mouse etc.
The java.awt.event to declared in package to provides many event classes
and Listener Interfaces for event handling.
A) 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.
B) . 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.
A) Sources
B) Listeners
A). 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.
B) Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for
handling events.
Events Classes and Event Listerners
or not.
Button
MenuItem
TextField
TextArea
Checkbox
Choice
List
Example: Write a java program how to create mouse event handling method.
import java.awt.*;
import java.awt.event.*;
public class ButtonE {
public static void main(String[] args)
{
Frame f = new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() // Mouse Event Handling Method
{
public void actionPerformed (ActionEvent e) // Action Event Method
{
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
OUTPUT:
Handling Mouse and Keyboard Events Interfaces
MouseListners Interface:
The Java MouseListener is notified whenever you change the state of mouse.
1. import java.awt.*;
2. import java.awt.event.*;
public class MouseMotionListenerE extends Frame implements
MouseMotionListener{
3. MouseMotionListenerE(){
4. addMouseMotionListener(this);
5. setSize(300,300);
6. setLayout(null);
7. setVisible(true);
8. }
9. public void mouseDragged(MouseEvent e) {
10. Graphics g=getGraphics();
11. g.setColor(Color.BLUE);
12. g.fillOval(e.getX(),e.getY(),20,20);
13. }
14. public void mouseMoved(MouseEvent e) {}
15. public static void main(String[] args) {
16. new MouseMotionListenerE();
17. }
18. }
OUTPOUT:
Java Key Board Events Interface
Example :
public class KeyListener extends Frame implements Key
Listener
5. Label l;
6. TextArea area;
7. // class constructor
8. KeyListenerExample2() {
9. // creating the label
10. l = new Label();
11. // setting the location of label
12. l.setBounds (20, 50, 200, 20);
13. // creating the text area
18. area.addKeyListener(this);
19. // adding label and text area to frame
20. add(l);
21. add(area);
35. }
36. public void keyTyped(KeyEvent e) {}
37. // main method
OUTPUT:
Java Adapter Classes
Java adapter classes provide the default implementation
of listener interfaces.
It assists the unrelated classes to work combined.
It provides ways to use classes in different ways.
It increases the transparency of classes.
It provides a way to include related patterns in the
class.
It provides a plug-gable kit for developing an
application.
It increases the re-usability of the class.
The adapter classes are declared in java.awt.event,
and javax.swing.event packages.
List of Adapter classes and Listener Interfaces
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
6. Frame f;
7. // class constructor
8. MouseAdapterE() {
9. // creating the frame with the title
12. f.addMouseListener(this);
13. // setting the size, layout and visibility of the frame
14. f.setSize (300, 300);
15. f.setLayout (null);
16. f.setVisible (true);
17. }
18. // overriding the mouseClicked() method of the
MouseAdapter class
19. public void mouseClicked (MouseEvent e)
20. {
30. {
33. }
OUTPUT:
Module-IV
PART-B
Java Layout Managers
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.
Layout Managers is an interface that is implemented by all the
classes of layout managers.
There are the following classes that represent the layout managers:
A) . Border Layout:
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:
OUTPUT:
B. Grid Layout :
The Java GridLayout class is used to arrange the components in a
rectangular grid.
One component is displayed in each rectangle.
OUTPUT:
C. Flow Layout:
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.
4.
6. FlowLayoutE()
7. {
22.
25. frameObj.add(b3);
26. frameObj.add(b4);
27. frameObj.add(b5);
28. frameObj.add(b6);
29. frameObj.add(b7);
30. frameObj.add(b8);
31. frameObj.add(b9);
32. frameObj.add(b10);
35. frameObj.setVisible(true);
36. }
38. {
41. }
OUTPUT:
D. Card Layout :
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.
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
public class CardLayoutE extends JFrame implements
ActionListener{
4. CardLayout card;
5. JButton b1,b2,b3;
6. Container c;
7. CardLayoutE(){
8. c=getContentPane();
9. card=new CardLayout(40,30);
10. //create CardLayout object with 40 hor space and 30
ver space
11. c.setLayout(card);
12. b1=new JButton("Apple");
13. b2=new JButton("Boy");
14. b3=new JButton("Cat");
15. b1.addActionListener(this);
16. b2.addActionListener(this);
17. b3.addActionListener(this);
18. c.add("a",b1);
19. c.add("b",b2);
20. c.add("c",b3);
21. }
22. public void actionPerformed(ActionEvent e)
23. card.next(c);
24. }
25. public static void main(String[] args) {
CardLayoutE cl=new CardLayoutE();
26. cl.setSize(400,400);
27. cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
28. } }
OUTPUT:
E. Grid Bag Layout:
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.
With the help of the constraints object, we arrange
the component's display area on the grid.
The GridBagLayout manages each component's
minimum and preferred sizes in order to determine
the component's size.
GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes
and can occupy multiple rows or columns.
Constructor:
GridBagLayout(): The parameterless constructor is used
to create a grid bag layout manager.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. public class GridBagLayoutE extends JFrame{
2. public static void main(String[] args) {
3. GridBagLayoutE a = new GridBagLayoutE();
4. }
5. public GridBagLayoutE() {
6. GridBagLayoutgrid = new GridBagLayout();
7. GridBagConstraints gbc = new GridBagConstraints();
8. setLayout(grid);
9. setTitle("GridBag Layout Example");
10. GridBagLayout layout = new GridBagLayout();
11. this.setLayout(layout);
12. gbc.fill = GridBagConstraints.HORIZONTAL;
13. gbc.gridx = 0;
14. gbc.gridy = 0;
15. this.add(new Button("Button One"), gbc);
16. gbc.gridx = 1;
17. gbc.gridy = 0;
18. this.add(new Button("Button two"), gbc);
19. gbc.fill = GridBagConstraints.HORIZONTAL;
20. gbc.ipady = 20;
21. gbc.gridx = 0;
22. gbc.gridy = 1;
23. this.add(new Button("Button Three"), gbc);
24. gbc.gridx = 1;
25. gbc.gridy = 1;
26. this.add(new Button("Button Four"), gbc);
27. gbc.gridx = 0;
28. gbc.gridy = 2;
29. gbc.fill = GridBagConstraints.HORIZONTAL;
30. gbc.gridwidth = 2;
31. this.add(new Button("Button Five"), gbc);
32. setSize(300, 300);
33. setPreferredSize(getSize());
34. setVisible(true);
35. setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37. }
OUTPUT:
Java Lists Panels
The Java List Panel is a simplest container class.
It provides space in which an application can attach
any other component.
It inherits the Container class.
Types of Java Lists Panels:
There are four different types of lists Panels. They are
a). Scroll pane
b). Dialog pane
c). Menu bar pane
d). Graphic pane
Constructor/Method Purpose
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JScrollPaneE {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane
(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScroll
Pane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPa
ne.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
createAndShowGUI();
});
}
}
OUTPUT:
b). Java Dialog Box Class:
The JDialog control represents a top level window with
a border and a title used to take some form of input
from the user.
It inherits the Dialog class.
Commonly used Constructors:
Constructor Description
3. import java.awt.event.*;
6. DialogE() {
7. JFrame f= new JFrame();
8. d = new JDialog(f , "Dialog Example", true);
9. d.setLayout( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. b.addActionListener ( new ActionListener()
12. {
13. public void actionPerformed( ActionEvent e )
14. {
15. DialogE.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continue."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(true);
22. }
23. public static void main(String args[])
24. {
25. new DialogE();
26. }
27. }
OUTPUT:
2. Import java.awt.*;
3. Import java.awt.event.:
4. class MenuE
5. {
32. {
34. }
35. }
OUTPUT:
D. Graphics Pane:
Java.awt.Graphics class provides many methods for
graphics programming in java.
Example: Write a java how to create a graphics.
1. import java.awt.*;
2. import javax.swing.
3. import java.awt.event.*;
4. public class DG extends Canvas{
5. public void paint(Graphics g) {
6. g.drawString("Hello", 40,40);
7. setBackground(Color.WHITE);
9. g.drawOval(30,130,50, 60);
10. setForeground(Color.RED);
14. }
15. public static void main(String[] args)
16. {
17. DG m=new DG();
18. JFrame f=new JFrame();
19. f.add(m);
20. f.setSize(400,400);
21. //f.setLayout(null);
22. f.setVisible(true);
23. }
24. }
OUTPUT: