Event and GUI programming

103
Event and GUI programming 1

description

Event and GUI programming. Event Handling in Java. An object resides in a particular state until it is made to transit to other state. This transition occurs due to an event . - PowerPoint PPT Presentation

Transcript of Event and GUI programming

Page 1: Event and GUI programming

1

Event and GUI programming

Page 2: Event and GUI programming

2

Event Handling in Java• An object resides in a particular state until it is made to

transit to other state. This transition occurs due to an event.

• We want an object to invoke a function when an action is generated, e.g. pressing a key on the keyboard, moving the mouse, clicking on button, etc.

• The object which generates event, i.e. the source of the event is known as the event generator.

• If a button is pressed for an operation, the button is the event generator.

• The object that is responsible for performing the task when the event occurs is called the event handler.

• There may be more than one event handlers for one single event generated; each event handler responsible for doing a unique activity on account of that particular event

Page 3: Event and GUI programming

3

• How handlers know that a particular event has occurred so that they can perform their activity?

• For this, there is a registration process. This registration involves the event handler simply asking the event generator to inform about the occurrence of an event.

• By registering, the event generator is able to keep track of all the registered event handlers.

Page 4: Event and GUI programming

4

Event Delegation Model• The Event Model Is Based on the Concept of an

‘Event Source’ and ‘Event Listeners’. – Any Object That Is Interested in Receiving

Messages (or Events ) Is Called an Event Listener.

– Any Object That Generates These Messages (or Events ) Is Called an Event Source.

Page 5: Event and GUI programming

5

Page 6: Event and GUI programming

6

• The Event Source Object Maintains a List of Listeners Who Are Interested in Receiving Events That It Produces.

• The Event Source Object Provides Methods That Allow the Listeners to Add Themselves ( ‘Register’ ) or Remove Themselves From This List of ‘Interested’ Objects.

• When the Event Source Object Generates an Event, or When a User Input Event Occurs on the Event Source Object, the Event Source Object Notifies All the Listeners That the Event Has Occurred.

Page 7: Event and GUI programming

7

Java.Awt.Event Description• The java.awt.AWTEvent class is the root class

for all AWT Events. • This package java.awt.AWTEvent includes the

definition of events classes, listeners interfaces, and adapters classes, which from the basics for event handling.

Page 8: Event and GUI programming

8

Event Classes• Java has a predefined hierarchy of event-

related classes, at the root of which is EventObject.

• It is actually a member of java.util package. This class has constructors and methods defined as its members.

• One such constructor is EventObject(Object src_obj)– where, src_obj is the object, which generates the

event.• EventObject has methods like getSource()

and toString().– getSource() – returns the source of the event– toString() – returns the string equivalent of the

event

Page 9: Event and GUI programming

9

Event Classes

Page 10: Event and GUI programming

10

KeyEvent Class• Syntax

public class KeyEvent extends InputEvent• This low-level event is generated by a

component object(such as text field, Applet, Frame) when a key is pressed, released, or typed.

• The event is passed to a KeyListener object which is registered to receive the event notification using the component’s addKeyListener method

Page 11: Event and GUI programming

11

Constructor

Page 12: Event and GUI programming

12

Methods in KeyEvent

Page 13: Event and GUI programming

13

MouseEvent

• It is an event which indicates that a mouse action occurred in a component.

• A mouse action occurs in a particular component if and only if the mouse cursor is over the defined part of the component’s bounds when the action happens.– public class MouseEvent extends InputEvent

• There are eight types of mouse events defined in the MouseEvent class.

• The MouseEvent class defines them as integer constants to identify each of these events.

Page 14: Event and GUI programming

14

types of mouse events

Page 15: Event and GUI programming

15

Constructor

Page 16: Event and GUI programming

16

Methods of MouseEvent

Page 17: Event and GUI programming

17

Source of Events

• Button• Choice• Menu Item• Check box• List• Window• Scroll bar• Text components

Page 18: Event and GUI programming

18

Source of Events

• Event Listeners are created by implementing one or more interfaces defined by the java.awt.event package.

• Whenever a source generates an event, it basically invokes the appropriate method defined in the listener interface.

• The method has a event object passed as an argument to it.

Page 19: Event and GUI programming

19

Listeners

Page 20: Event and GUI programming

20

KeyListener

This interface has three methods defined within it. void keyPressed(KeyEvent e) – invoked when a key is pressed void keyReleased(KeyEvent e) - invoked when a key is released void keyTyped(KeyEvent e) - invoked when a character is typed

Page 21: Event and GUI programming

21

MouseListener

The interface has five methods, having the signatures as follows: void mouseClicked(MouseEvent e) void mouseEntered(MouseEvent e) void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e) void mouseExited(MouseEvent e)

Page 22: Event and GUI programming

22

MouseMotionListener

The interface has two methods having the signatures,void mouseMoved(MouseEvent e)void mouseDragged(MouseEvent e)

mouseMoved() is invoked when the mouse is moved from one place to another and mouseDragged() is used when the mouse is dragged.

Page 23: Event and GUI programming

23

MouseWheelListener

Page 24: Event and GUI programming

24

ItemListener

Page 25: Event and GUI programming

25

ActionListener

Page 26: Event and GUI programming

26

TextListener

Page 27: Event and GUI programming

27

Example

Page 28: Event and GUI programming

28

Output

Page 29: Event and GUI programming

29

AWT• AWT provides graphical user interface (GUI)

components that are used in all java applet and application

• AWT contains classes that can be extended and their properties can be inherited

Page 30: Event and GUI programming

30

Java.awt package• The package java.awt contain all classes used for

creating graphical user interfaces, painting graphics, images, color, and fonts.

• A user interface element such as a button or a textbox is called a component

• A Component class is the super class of all AWT components.

• These components fire events when users interact with these components, e.g. when a user click on a button. These events are handled by event handling classes. i.e. AWTEvent and its subclasses.

• A container is one which contains components and other containers. A container has a layout managers that determines the visual placement of components in the container.

Page 31: Event and GUI programming

31

Component and Containers• A graphical user interface is developed with the help of

graphical elements like buttons, scrollbar etc.• These elements are called components. These

components are generally the source of events that allow the user to interact with the program.

• Componenets are added to a window using the add() method– Component add(Component ComObj)– ComObj is the object of the Component, which is to be

added– This method returns the reference to the ComObj.

• If you wish to remove a Component from a window, use remove() method– void remove(Component ComObj)2

• Components can not exist alone; they are found within containers. The layout of the components are contained and controlled within containers.

Page 32: Event and GUI programming

32

Hierarchy of classes in AWT

Page 33: Event and GUI programming

33

Page 34: Event and GUI programming

34

Button• The Button class belongs to java.awt package

– public class Button extends Component implements Accessible• This class creates a button which when pushed or

pressed generates an event. • The two constructors belonging to this Button class are:

– Button() throws HeadlessException– Button(String str)throws HeadLessException;

• To create a button – Button buttonName = new Button(Str);– ‘buttonname’ is the name you give to the button object and ‘Str’ is

the text you want to appear on the button. • Once the object for Button is created, it needs to be

added to the applet or any other container using– add(buttonname);– void setLabel(String str) for changing the button’s label– String getLabel() for getting the Buttons label’s text

Page 35: Event and GUI programming

35

• Syntax : -Button buttonname=new Button(Str);Where buttonname is the name of the

button object and str is the text we want to appear on the button• Once the object for Button is created, it needs

to be added to the applet or any other containers.

• The syntaxadd(buttonname)

Page 36: Event and GUI programming

36

Button Example

/*<applet code=ButtonClass.class width=400 height=150></applet>*/

import java.applet.*;import java.awt.*;import java.awt.event.*;public class ButtonClass extends Applet implements

ActionListener{Button red, white, blue;Label hit;public void init(){red = new Button(“Red”);white = new Button(“white”);blue = new Button(“blue”);hit = new Label(“Hit a Button to change the screen

color”);add(red); add(white); add(blue); add(hit);

Page 37: Event and GUI programming

37

Button Example

red.addActionListener(this);white.addActionListener(this);blue.addActionListener(this);}public void actionPerformed(ActionEvent ae){String str = ae.getActionCommand();if (str.equals(“Red”)) {setBackground(Color.red);}else if (str.equals(“white”)) {setBackground(Color.white);}else if (str.equals(“blue”)){setBackground(Color.blue);}repaint();}}

Page 38: Event and GUI programming

38

Output

Page 39: Event and GUI programming

39

Label• Labels consist of a text string for display only and they

never call an action method.• A Label can be justified LEFT, RIGHT, or CENTERED.

– new Label(“This label is for demonstration.”, Label.RIGHT);

Page 40: Event and GUI programming

40

Label Example

/*<applet code=”LabelClass.java” width=350 height=100></applet>*/import java.applet.*;import java.awt.*;public class LabelClass extends Applet {public void init(){Label firstLabel = new Label(“Labels exist simply “);add(firstLabel);Label secLabel = new Label(“to place text on the screen”);add(secLabel);Label thirdLabel = new Label(“They can be aligned left, right or center.”);add(thirdLabel);}}

Page 41: Event and GUI programming

41

CheckBox

• Checkboxes are used as on-off or yes-no switches

• if you click on an unchecked checkbox, it will get checked and vice versa.

• Constructors of Checkbox– Checkbox()– Checkbox(String str)– Checkbox(String str, boolean on)– Checkbox(String str, CheckBoxGroup cbg, boolean

on)

Page 42: Event and GUI programming

42

Methods of Checkbox class

Page 43: Event and GUI programming

43

Page 44: Event and GUI programming

44

Checkbox Example/*<applet code=CheckboxClass.class width=400 height=100></applet>*/import java.applet.*;import java.awt.*;import java.awt.event.*;public class CheckboxClass extends Applet implements ActionListener {Button submit;Checkbox name1;Checkbox name2;Checkbox name3;public void init(){name1 = new Checkbox (“Ram”,null,false);name2 = new Checkbox (“Ramesh”,null,false);name3 = new Checkbox (“Naresh”,null,false);

Page 45: Event and GUI programming

45

Checkbox Example

Font f = new Font (“Arial”,Font.ITALIC,14);submit = new Button(“SUBMIT”);add(name1); add(name2); add(name3); add(submit);submit.addActionListener(this); }public void actionPerformed(ActionEvent ae) {String str = ae.getActionCommand();if (str.equals(“SUBMIT”)) repaint();}public void paint (Graphics g) {g.setFont(f);g.setColor(Color.blue);if (name1.getState())g.drawString(“Ram”,50,60);if (name2.getState())g.drawString(“Ramesh”,50,80);if (name3.getState())g.drawString(“Naresh”,50,100); }}

Page 46: Event and GUI programming

46

The Output

Page 47: Event and GUI programming

47

RadioButton• Radio buttons, which are also called checkbox

groups, are special kind of checkboxes, where within a particular group, only one box can be selected at a time

Checkbox cb=new Checkbox(“mango”,fruits,false);• First argument is label, the second argument is

the group of which it is a part of, and the third is the state, true or false, depending on whether the button is the selected or not

Page 48: Event and GUI programming

48

Page 49: Event and GUI programming

49

Radio Button Example

/*<applet code=”RadioDemo.class” width=300 height=200></applet>*/import java.applet.*; import java.awt.*;import java.awt.event.*;public class RadioDemo extends Applet implements ItemListener{Checkbox red, white, green; CheckboxGroup cbg;public void init(){add(new Label(“The 4 radio buttons will change the screen color.”));cbg = new CheckboxGroup();red = new Checkbox(“Red”,cbg,false);white = new Checkbox(“White”,cbg,false);green = new Checkbox(“Green”,cbg,false);add(new Label(“Notice that you can only select one radio button.”));add(new Label(“And selecting a radio button triggers an event”));

Page 50: Event and GUI programming

50

Radio Button Example

add(new Label(“that we use to change the screen color.”));add(red);add(white); add(green);red.addItemListener(this);white.addItemListener(this);green.addItemListener(this); }public void itemStateChanged(ItemEvent ie){String str = (String) ie.getItem();if (str.equals(“Red”)) {

setBackground(Color.red);}else if (str.equals(“White”)) {

setBackground(Color.white);}else if (str.equals(“Green”)){

setBackground(Color.green);}repaint();}}

Page 51: Event and GUI programming

51

The Output

Page 52: Event and GUI programming

52

List Boxes

• The List class provides a multiple choice, scrolling list of values that may be selected alone or together

• A list can be created to show any number of choices in the visible window

• Constructors– List()

• In the default constructor case, only one item can be selected at a time

– List(int no_of_rows)• In this constructor, we can specify the number of rows in

the list that we want to be visible.– List(int no_of_rows, boolean multi_select)

• In this constructor, if the boolean value is set to true, it simply means that the user can select more than one item at a time from the list. If it is set to false, then only one item of the list can be selected at a time

Page 53: Event and GUI programming

53

• The simplest form of List that does not allow multiple selection can be created by the following syntax List list=new List()

• If we want to create a list that does not allow multiple selections, use the following command line which creates a list with 10 visible entries and multiple selection turned on.List list=new List(10,true)

Page 54: Event and GUI programming

54

Method

Page 55: Event and GUI programming

55

Choice Boxes

• The Choice class is a lot like lists, but it allows us to conserve space since it provides a pop-up menu of text string choices.

• The current choice is displayed on top.• In order to work with a choice box, an instance of the

Choice class must be created• Once we created the choice, the add method enables

us to add new entriesc.add(“Red”)

• The currently selected item can be changed by using select() method. The selection can be made based on name or index. For examplec.select(“Red”);Orc.select(0);

Page 56: Event and GUI programming

56

• The getSelectedIndex() method would return the position of the selected item and the getSelectItem() returns the name of selected item respectively.

Page 57: Event and GUI programming

57

Page 58: Event and GUI programming

58

Output

Page 59: Event and GUI programming

59

Text Field and Text Area

• The TextField and TextArea classes are two different Java classes for entering text data.

• The TextField class handles single line of text. The TextArea is used for handling multiple lines of text.

Page 60: Event and GUI programming

60

Constructor

Constructor DescriptionTextField() Constructs a new text field.

TextField(int columns) Constructs a new empty text field with the specified number of columns.

TextField(String text) Constructs a new text field initialized with the specified text.

TextField(String text, int columns) Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.

The following line will create a TextField with 20 columnsTextField pt=new TextField(20);

Page 61: Event and GUI programming

61

Page 62: Event and GUI programming

62

Page 63: Event and GUI programming

63

Constructor of TextAreaConstructor Description

TextArea() Constructs a new text area with the empty string as text.

TextArea(int rows, int columns) Constructs a new text area with the specified number of rows and columns and the empty string as text.

TextArea(String text) Constructs a new text area with the specified text.

TextArea(String text, int rows, int columns)

Constructs a new text area with the specified text, and with the specified number of rows and columns

TextArea(String text, int rows, int columns, int scrollbars)

Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

Page 64: Event and GUI programming

64

Methods

Page 65: Event and GUI programming

65

Page 66: Event and GUI programming

66

Page 67: Event and GUI programming

67

Output

Page 68: Event and GUI programming

68

Example

Page 69: Event and GUI programming

69

Page 70: Event and GUI programming

70

Container Class• Containers allow us to organize components

into manageable groups which are extremely important in order to create a good user interface.

• A component is the AWT can only be used if it is held within container.

Page 71: Event and GUI programming

71

Types of Containers

• Window : - it is a top-level display surface. An object of Window class is not attached to nor embedded within another container. An instance of the window does not have border, title bar or menu.

• Frame : - It is a top-level window with a border and title. An instance of the Frame class may have a menu bar, title bar and borders

• Dialog : - It is a top-level display surface with a border and title. An object of the Dialog class can not exist without an associated object of the Frame class

• Panel : - It is a generic container for holding components. An instance of the Panel class provides a container to which components can be added. It does not add any new method; it simply implements the container

Page 72: Event and GUI programming

72

Panels

• The definition of the Panel class is as follows

Public class Panel extends Container Implements Accessible• Panel is a window that does not contain a

title bar or a menu bar.• Component (like label, button etc) can be

added to the panel object by using the add() method.

• The add() method actually belongs to the container class, the super class of the Panel class

Constructor Description

Panel() Creates a new panel using the default layout manager

Panel(LayoutManager layout) Creates a new panel with the specified layout

Page 73: Event and GUI programming

73

How to Use Panels

• Create the Panel by writing the following piece of code

Panel panel=new Panel();• Add component to Panel by using add() method

panel.add(button);panel.add(label);

• If we want to add an external container, then we have to call the add() method in the following ways

Container.add(panel);• Or it we want to add from within a container,

then call the add() method directly

Page 74: Event and GUI programming

74

Window

• This class creates a top-level window. Top-level window means that it is not contained within any other object. It has the following signature

public class Window extends Container implements Accessible

• A Window object is a window with no border and no menubar. The default layout for a window is BorderLayout.

• A window must have a frame, dialog, or another window defined as its owner when it is constructed, out of which only Frame is most often used

Page 75: Event and GUI programming

75

Frame• Constructor• Frame()– This Constructor creates a Frame window

without any title• Frame(String title)– This one creates Frame with the title

specified as String in the argument

Page 76: Event and GUI programming

76

MethodsMethod Description

void setSize(int width, int height) It is used to set the dimension of window. The new dimension in the form of width and height is passes as argument

void setSize(Dimension size) Sets the size of the Frame with dimension specified

void setVisible(boolean flag) It is used to make the window visible after its creation. The component is visible only if the argument passed is true

void setTitle(String title) The title in the Frame window can be used to set to a new title, passed as argument

Page 77: Event and GUI programming

77

Example

Page 78: Event and GUI programming

78

Output

Page 79: Event and GUI programming

79

Layouts• Java has the mechanism to specify the type of

layout schemes, where components can be added to a Frame instance.

• This mechanism is specified by LayoutManager, which is used to specify how the components can be arranged inside a container, says a Frame.

• The various LayoutManagers available in AWT are children of this interface.

• This LayoutManager is actually an interface in java.awt, defined as:public interface LayoutManager

Page 80: Event and GUI programming

80

FlowLayOut

• Simplest layout manager• Components are placed left to right and

top-to- bottom in the order they are added

• There is five pixel gap between the components arranged in this layout

• Components can be left aligned, centered or right aligned

Page 81: Event and GUI programming

81

Constructor

Constructor DescriptionFlowLayout() Constructs a new FlowLayout with a

centered alignment and a default 5-unit horizontal and vertical gap.

FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap)

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Page 82: Event and GUI programming

82

Methods

Page 83: Event and GUI programming

83

Page 84: Event and GUI programming

84

Output

Page 85: Event and GUI programming

85

BorderLayout• This is the default layout of the Frame. The class

belonging to the java.awt, named as BorderLayout, has the following signature,

public class BorderLayout extends Object implements LayoutManager2, Serializable• Arranges components into five regions – north, south,

east, west and center• Implements interface LayoutManager2• Provides horizontal gap spacing and vertical gap spacing• Any of these constant names can be used while adding a

component to a container, for examplePanle pnl=new Panel();pnl.setLayout(“new BorderLayout());pnl.add(new Button(“submit”,

BorderLayout.NORTH)

Page 86: Event and GUI programming

86

Example

Page 87: Event and GUI programming

87

Output

Page 88: Event and GUI programming

88

GridLayout• The class belonging to java.awt, named as

GridLayout, has the following signaturepublic class GridLayout extends Object implements LayoutManager, Seriazable

• The GridLayout class is layout manager that lays out a container’s components in a rectangular grid.

• This is a Layout Manager which can be used to arrange controls in a container.

• GridLaylut has a specified number of rows and columns, where the container is divided into equal-sized rectangles, and one component is placed in each rectangle.

Page 89: Event and GUI programming

89

Page 90: Event and GUI programming

90

Page 91: Event and GUI programming

91

CardLayout• CardLayout class inherits Object class and

implements LayoutManager2, Serializable interface

• Object of cardLayout acts as layout manager for a container.

• In a container each component is treated as a card by CardLayout object.

• Each card kept on another like a stack and only one card can be visible at a time.

• When the container is displayed after adding the first component, then the first component is visible

Page 92: Event and GUI programming

92

Page 93: Event and GUI programming

93

Page 94: Event and GUI programming

94

Page 95: Event and GUI programming

95

Menu• Menu is class inherits MenuItem class and

two interfaces : MenuContainer and Accessible.

• Menubar deploys a menu object which is a dropdown menu component

• Constructors of Menu

Page 96: Event and GUI programming

96

MethodsMethods Description

Add(MenuItem) Adds the specified menu item to the menu

Add(String laabel) Adds an item with the specified label to the menu

deleteShortcut(MenuShortcut s)

Used to delete the menu shortcuts

getAccessibleContext() Gets the AccessibleContext associated with this menu

getItemCount() Gets the number of items in the menu

getItem(int index) Gets the item located at the given index of the menu

removeAll() Removes all items from the menu

Page 97: Event and GUI programming

97

Constructor of MenuBarMenuBar() :- Creates a new menubar

• Methods of MenubarMethods Description

Add(Menu m) Adds the particular menu to the menu bardeleteShortcut(Menu Shortcuts)

Used to delete the specified menu shortcut

getAccessibleContext()

Gets the AccessibleContext associated with this MenuBar

Shortcuts() Used to manager menu bar shortcut as an Enumeration

Remove(int index) Removes the menu placed at the specified index from the menubar

Page 98: Event and GUI programming

98

Constructor of MenuItem

Constructors DescriptionMenuItem() Constructs a new MenuItem with an blank

label and there is no keyboard shortcutMenuItem(String label)

Constructs a new MenuItem with the mentioned label and also there is no keyboard shortcut

MenuItem(String lable, MenuShortcut s)

Creates a menu item with particular shortcut

Page 99: Event and GUI programming

99

• MenuShortcut : - It inherits the Object class and implements Serializable interface. The MenuShortcut class acts as a keyboard accelerator for a MenuItem. These are not created by characters but by some keycodes like Ctrl –c, Ctrl -v

Constructor Description

MenuShortcut(int key) Constructs a menu shortcut with a keycode

MenuShortcut(int key, boolean useShiftModifier)

The menu shortcut is creates with a keycode and boolean value indicates that shift key be used with keycode

Page 100: Event and GUI programming

100

Page 101: Event and GUI programming

101

Page 102: Event and GUI programming

102

Output

Page 103: Event and GUI programming

103