Presentation is loading. Please wait.

Presentation is loading. Please wait.

Event and GUI programming 1. Event Handling in Java An object resides in a particular state until it is made to transit to other state. This transition.

Similar presentations


Presentation on theme: "Event and GUI programming 1. Event Handling in Java An object resides in a particular state until it is made to transit to other state. This transition."— Presentation transcript:

1 Event and GUI programming 1

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 2

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. 3

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. 4

5 5

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. 6

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. 7

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 8

9 Event Classes 9

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 10

11 Constructor 11

12 Methods in KeyEvent 12

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. 13

14 types of mouse events 14

15 Constructor 15

16 Methods of MouseEvent 16

17 Source of Events Button Choice Menu Item Check box List Window Scroll bar Text components 17

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. 18

19 Listeners 19

20 KeyListener 20 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

21 MouseListener 21 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)

22 MouseMotionListener 22 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.

23 MouseWheelListener 23

24 ItemListener 24

25 ActionListener 25

26 TextListener 26

27 Example 27

28 Output 28

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 29

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. 30

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. 31

32 Hierarchy of classes in AWT 32

33 33

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 34

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 syntax add(buttonname) 35

36 Button Example 36 /* */ 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);

37 Button Example 37 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();}}

38 Output 38

39 Label 39 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);

40 Label Example 40 /* */ 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);}}

41 CheckBox 41 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)

42 Methods of Checkbox class 42

43 43

44 Checkbox Example 44 /* */ 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);

45 Checkbox Example 45 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);}}

46 The Output 46

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 47

48 48

49 Radio Button Example 49 /* */ 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”));

50 Radio Button Example 50 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();}}

51 51 The Output

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 52

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) 53

54 Method 54

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 entries c.add(“Red”) The currently selected item can be changed by using select() method. The selection can be made based on name or index. For example c.select(“Red”); Or c.select(0); 55

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

57 57

58 Output 58

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. 59

60 Constructor 60 ConstructorDescription TextField() 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 columns TextField pt=new TextField(20);

61 61

62 62

63 Constructor of TextArea ConstructorDescription 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. 63

64 Methods 64

65 65

66 66

67 Output 67

68 Example 68

69 69

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. 70

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 71

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 72 ConstructorDescription Panel()Creates a new panel using the default layout manager Panel(LayoutManager layout)Creates a new panel with the specified layout

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 73

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 74

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 75

76 Methods MethodDescription 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 76

77 Example 77

78 Output 78

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 79

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 80

81 Constructor 81 ConstructorDescription FlowLayout()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.

82 Methods 82

83 83

84 Output 84

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 example Panle pnl=new Panel(); pnl.setLayout(“new BorderLayout()); pnl.add(new Button(“submit”, BorderLayout.NORTH) 85

86 Example 86

87 Output 87

88 GridLayout The class belonging to java.awt, named as GridLayout, has the following signature public 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. 88

89 89

90 90

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 91

92 92

93 93

94 94

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 95

96 Methods 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(MenuShor tcut 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 96

97 Constructor of MenuBar MenuBar() :- Creates a new menubar Methods of Menubar 97 MethodsDescription Add(Menu m)Adds the particular menu to the menu bar deleteShortcut(M enu Shortcuts) Used to delete the specified menu shortcut getAccessibleCont ext() 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

98 Constructor of MenuItem ConstructorsDescription MenuItem()Constructs a new MenuItem with an blank label and there is no keyboard shortcut MenuItem(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 98

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 99 ConstructorDescription 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

100 100

101 101

102 Output 102

103 103


Download ppt "Event and GUI programming 1. Event Handling in Java An object resides in a particular state until it is made to transit to other state. This transition."

Similar presentations


Ads by Google