Tuesday, January 23, 2018

Programming With JAVA Unit 5 : GUI Using SWING Event Handling for BCA,B.Sc(IT),MCA,M.Sc(IT) and All IT Students


--------------------------------------------------------------------------------------------------------------------------
Prepared By : Uday Shah(HOD-IT)
Contact No  : +91 7600044051
E-Mail         : rupareleducation@gmail.com

Programming With JAVA
Unit 5 : GUI Using SWING Event Handling  

Question : What is AWT?
The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. AWT is Effective graphical user interfaces are inherently challenging to design and implement more complex task. It is a simple user interface for an applet or application.

AWT
·        AWT stands for Abstract windows toolkit.
·        AWT components are called Heavyweight component.
·        AWT components require java.awt package.
·        AWT components are platform dependent.
·        AWT is a thin layer of code on top of the OS.
·        Using AWT, you have to implement a lot of things yourself.

Question : What is Swing?
Java Swing is a lightweight Java graphical user interface (GUI) widget toolkit that includes a rich set of widgets. It is part of the Java Foundation Classes (JFC) and includes several packages for developing rich desktop applications in Java. Swing includes built-in controls such as trees, image buttons, tabbed panes, sliders, toolbars, color choosers, tables, and text areas to display HTTP or rich text format (RTF). Swing components are written entirely in Java and thus are platform-independent.

Swing
·        Swing is also called as JFC’s (Java Foundation classes).
·        Swings are called light weight component because swing components sits on the top of AWT components and do the work.
·        Swing components require javax.swing package.
·        Swing components are made in purely java and they are platform independent.
·        We can have different look and feel in Swing.
·        Swing has many advanced features like JTabel, Jtabbed pane which is not available in AWT. Also. Swing components are called "lightweight" because they do not require a native OS object to implement their functionality. JDialog and JFrame are heavyweight, because they do have a peer. So components like JButton, JTextArea, etc., are lightweight because they do not have an OS peer.
·        With Swing, you would have only one peer, the operating system's window object. All of the buttons, entry fields, etc. are drawn by the Swing package on the drawing surface provided by the window object. This is the reason that Swing has more code. It has to draw the button or other control and implement its behavior instead of relying on the host operating system to perform those functions.
·        Swing is much larger. Swing also has very much richer functionality.
·        Swing has them built in.

Question : Difference Between AWT and Swing  

No.
Java AWT
Java Swing
1
AWT components are platform-dependent.
Java swing components are platform-independent.
2
AWT components are heavyweight.
Swing components are lightweight.
3
AWT doesn't support pluggable look and feel.
Swing supports pluggable look and feel.
4
AWT provides less components than Swing.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5
AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view.
Swing follows MVC.



Question : Swing Component



Java JFrame



The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.
Java JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.

Java JLabel


The object of JLabel 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 an application but a user cannot edit it directly. It inherits JComponent class.

Java JButton


The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.

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.
It should be added in ButtonGroup to select one radio button only.

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.

Java JTextField

 

The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class.

Java JPasswordField

 

The object of a JPasswordField class is a text component specialized for password entry. It allows the editing of a single line of text. It inherits JTextField class

Java JTextArea

 

The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits JTextComponent class
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.

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

The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
JMenu
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.
JMenuItem

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of its subclass.

JToggleButton
A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices.


JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class.

Java JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range.

Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits JComponent class.

Java JTextPane
JTextPane is a subclass of JEditorPane class. JTextPane is used for styled document with embedded images and components. It is text component that can be marked up with attributes that are represented graphically. JTextPane uses a DefaultStyledDocument as its default model.


Question : What is an Event?


Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.

Question : Types of Event

The events can be broadly classified into two categories:
·        Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc.
·        Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.


Question : What is Event Handling?


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. This model defines the standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
·        Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. An event source is a component, such as a GUI component, that generates an event. The event source can be generated by any type of user interaction. You can also combine a number of different types of events into one event object.  For example, if a user clicks and drags an icon, you can sum up the mouse-clicked event and the mouse-moved event into one event object.  In the event delegation model, a class represents each event type. Event objects are all defined in the java.util.EventObject subclasses. 
·        Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them.


Question : Steps involved in event handling


·        The User clicks the button and the event is generated.
·        Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
·        Event object is forwarded to the method of registered listener class.
·        the method is now get executed and returns.

Points to remember about listener


·        In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class.
·        If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.


Question : Callback Methods


These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the  source must register itself to the listener.

Event delegation Model

It is important to consider how users interact with the user interface when designing a graphical user interface (GUI). The GUI may require users to click, resize, or drag and drop components of the interface, and input data using the keyboard. These actions will result to an event and you need to write a code to handle them.
Event handling code deals with events generated by GUI user interaction. The best practices for coding event handlers are outlined in the event delegation model.
The event delegation model comprises three elements:
  • Event source
  • Event listener
  • Adapter
Event source :
An event source is a component, such as a GUI component, that generates an event. The event source can be generated by any type of user interaction. You can also combine a number of different types of events into one event object. 
For example, if a user clicks and drags an icon, you can sum up the mouse-clicked event and the mouse-moved event into one event object.

In the event delegation model, a class represents each event type. Event objects are all defined in the 
java.util.EventObject subclasses.

A generated event object 
·         provides the methods to add or remove the source event
·         manages the list of registered event listeners
·         provides the appropriate class type to the registered event listeners
Event listener :

Event listeners are objects that receive notification of an event. Components define the events they fire by registering objects called listeners for those event types. When an event is fired, an event object is passed as an argument to the relevant listener object method. The listener object then handles the event.

To receive notification of an event, the object must be registered with the event source. To subscribe to the event source, you implement the appropriate listener interface. 

All listeners are implementations of the 
EventListener interface or one of its subinterfaces. The Java API provides a predefined listener interface for each set of event types that a source can fire. For example, the MouseListenerinterface deals with mouse events, and the ActionListener interface deals with action events fired by buttons and other components.

Each listener interface provides at least one method for delivering the event object to the listener, in addition to any methods required for the action. All methods take one parameter and are part of the 
EventObject class.

Adapter :
Adapters are abstract classes that implement listener interfaces using predefined methods. These are provided for convenience.

You can use an adapter to apply one listener's methods without having to implement all other methods. Adapters provide empty implementations for all interfaces' methods, so you only need to override the method you are interested in.



Question : AWT Event Packages :

·        The AWT event is a subclass of EventObject and is a part of the java.awt. package.
·        AWTEvent is an abstract class.
·        All of the AWT Event types are sub classes of AWTEvent.
·        Constructor of AWTEvent is as follow
o       AWTEvent(Object source , int id)
·        According to above Constructor source is the object that generate the event and id identifies the type of the event. And id is define for identification of control.
·        The java.awt.event define several types of event that are generated by various user interface elements.

Question : Swing Event Package




  • The javax.swing.event package augments the java.awt.event package and defines event objects, listeners, and adapters that are specific to Swing components.
  • Classes with names ending in "Event" define event types; their fields and methods provide details about the event that occurred.
  • Interfaces with names ending in "Listener" are event listeners.
  • The methods of these interfaces are invoked to notify interested objects when specific events occur.

Event Class
Description
ActionEvent
Generated when a button is pressed, a list item is double – clicked, or a menu item is selected.
AdjustmentEvent
Generated when a scroll bar is manipulated.
ComponentEvent
Generated when a component is hidden, moved ,resized  or becomes visible.
ContainerEvent
Generated when a component is added to or removed from a container.
FocusEvent
Generated when a component gain or loses keyboard focus.
InputEvent
Abstract subclass for all component input event classes.
KeyEvent
Generated when input is received from the keyboard
MouseEvent
Generated when the mouse is dragged, moved, clicked, pressed or released , also generated when the mouse enters or exits a component.
MouseWheelEvent
Generated when the mouse wheel is moved.
TextEvent
Generated when the value of a text area or a text filed is changed.
WondowEvent
Generated when a window is activated, closed, deactivated,  open or quit


AWTEvent Summary

Event Type
Event Source
Event Listener
Event Handler
Action Event
·        Button
·        List
·        Menuitem
·        TextField
ActionListener
ActionPerformed
AdjustmentEvent
·        Scrollbar
AdjustmentListener
AdjustmentValueChanged (AdjustmentEvent e)
ItemEvent
·        Choice
·        Checkbox
·        CheckboMenuItem
·        List
ItemListener
Item Statechanged (itemEvent e)
TextEvent
·        TextField
·        TextArea
TextListener
TextValueChaged(TextEvent e)
KeyEvent
·        Cinoibebt
KeyListener
KeyPressed (KeyEvent e)
KeyReleased(KeyEvent e)
KeyTyped(KeyEvent e)
Mouse Event
·        Component
Mouse Listener
MouseClicked(MouseEvent e)
MouseEntered(MouseEvent e)
MouseExited(MouseEvent e)
MousePressed(MouseEvent e)
Mouse Motion Listener
Mouse Released(Mouse Event e)
Mouse Moved(Mouse Event e)
Mouse Dragged(Mouse Event e)
FocusEvent
·        Component
FocusListener
focusGained(FocusEvent e)
focusLost(FocusEvent e)
WindowEvent
·        Window
WindowListener
windowOpened(windowEvent e)
windowClosing(windowEvent e)
windowClosed((windowEvent e)
windowOpened(windowEvent e)
windowIconified(windowEvent e)


Question : Action Event

An action event is generated when a button is pressed, a list item is double – clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modification associated with an action event. Action event has three constructors.
1.             ActionEvent (Object src, int type, String cmd)
2.             ActionEvent (Object src, int type, String cmd, int modifiers)
3.           ActionEvent (Object src, int type, String cmd, long when, int modifiers)
According to above syntax src is reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The modifiers indicate which modifier keys were pressed when the event was generated. And when specifies when the event occurred.


Question : Item Event
An Item Event is generated when a check box or a list item is clicked  or when a checkable menu item is selected or deselected. There are two types of item events, which are identified by integer constants.

DESELECTED = the user deselected an item
SELECTED = the user selected an item
Constructor for ItemEvent is as follow:

          ItemEvent (ItemSelectable src, int type ,Object entry, int state)

According to above syntax src is a reference to the component that generated this event. The type of the event is specified by type. The specified item that generated the item event is passed in entry.

Question : Focus Event
A FocusEvent is generated when a component gains or loses input focus. This event are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent and has three constructors.
FocusEvent (Component src, int type)
FocusEvent (Component src, int type, Boolean tempflag)
FocusEvent (Component src, int type, Boolean tempflag, component other)
According to above syntax src is reg to the component that generated this event. The type of the event is specified by type. The argument tempflag is set to true if the focus event is temporary.



Question : Mouse Event
Mouse event is a subclass of  inputevnt. There are eight types of mouse events. The MouseEvent class defines the following integers constants that can be used to identified them.
·        MOUSE_CLICKED      -        user click the moue button
·        MOUSE_DRAGGED              user dragged the mouse
·        MOUSE_ENTERED               mouse enter a component
·        MOUSE_EXITED                   mouse exited from a component
·        MOUSE_MOVED                            mouse moved
·        MOUSE_PRESSED                mouse was pressed
·        MOUSE_RELEASED             mouse was released
·        MOUSE_WHEEL                             mouse wheel was moved

Mouse event has the following constructor.

          MouseEvent(Component src, it type, long when, int modifiers, int x ,int y, int clicks, Boolean triggers)

According to above syntax src is reference to the generate the event. The type of the event is specified by type. The system item at which the mouse event occurred is passed in when. The modifiers arguments indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y.
          The most commonly used method in the class are getX() and getY(). This return the X and Y coordinates of he mouse when the event occurred.

Question : MouseWheelEvnet
The mouse wheel event class encapsulates a mouse wheel event. It is a subclass of Mouse Event. MouseWheelEvent defines two integer constant.
·        WHEEL_BLOCK_SCROLL   - A Page up or Page down scroll event occurred.
·        WHEEL_UNIT_SCROLL       - A line Up or line down scroll event occurred.

Following is constructor of MouseWheelEvent

         MouseWheelEvent(Component src, int type, long when, int modifiers, int x int y, int clicks, Boolean trigger, int count)

According to above src is a reference to the object that generated the event. The type of the event is specified by type. The modifier argument indicates which modifies were pressed when the event occurred. The coordinate of the mouse are passed in x and y. the number of clicks the wheel has rotated is passed in clicks.


Question : TextEvent
Text Event are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.
Following is constructor of TextEvent
          TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by type.



Question : WindowEvent

Window event is a subclass of component Event. There are ten types of window events.

·        WINDOW_ACTIVAED                             - the window was activated.
·        WINDOW_CLOSED                        - window has been closed.
·        WINDOW_CLOSING                       - User request that the window be closed.
·        WINDOW_DEACTIVATED           - window was deactivated.
·        WINDOW_DEICONIFIED              - window was deiconified.
·        WINDOW_GAINED_FOCUS                   - window gained input focus.
·        WINDOW_ICONIFIED                    - window was iconified.
·        WINDOW_LOST_FOCUS               - window lost input focus.
·        WINDOW_OPENED                       - window was opened.
·        WINDOW_STATE_CHANGED      - the state of the window changed.

ComponentEvent defines several constructors
          WindowEvent (window src, int type)
          WindowEvent (window src, int type, window other)
          WindowEvent (window src, int type, int fromstate, int tostate)
          WindowEvent (window src, int type, window other, int fromstate, int tostate)
According to above syntax src is a reference to the object that generated this event, The type of the event is type. Other specifies the opposite window when a focus event occurs. The fromstate specifies the prior state of the window and tostate is specifies the new state of the window.



Event Listener Interface

The delegation event model has two parts source and listener. Listener are create by implementing one or more of the interface defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provide an event object as its argument.

Interface
Description
ActionListener
Defines one method to receive action events. Action Listener interface defines the actionPerformed() Method that is invoked when an action event occurs.
AdjustmentListener
Defines one method to recognize when a component is hidden, moved, resized or shown. AdjustmentListener interface defines tge adhystnebt ValueChanged() method that is invoked when an adjustment event occurs.
ComponentListener
Define  methods to recognize when a component is hidden, moved, resized or shown.
FocusListener
Define Method to recognize when a component gains or loss keyboard focus.
ItemListener
Define method to recognize when the state of tn item changes.
KeyListener
Define method to recognize when key is pressed, released or typed.
MouseListener
Define method to recognized when the mouse is clicked, event or component, exits a component is pressed or is released.
MouseMotionListener
Define method to recognize when the mouse is dragged or moved.
MouseWheelListener
Define method to recognize when  the mouse wheel is moved.
TextListener
Define method to recognize when a text value is changes.
WindowFocusListener
Drfine method to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened or quit.



Adapter Class

When we implement an interface is any program then we must implement all the methods declared in that interface.  
For example, in our program we have implemented MouseListener.  This MouseListener interface declare five method. However, it must implement all of the five method declare by that interface.
This can be inconvenient because if we want to use only one or two methods when? Adapter classes make it easy to deal with this situation. An adapter class provide empty implementation of all methods in a particular listener interface. It can be useful if you want to override only some of the method defined by that interface.

Following is an adapter class table

Adapter Class
Listener Interface
ComponentAdapter
ComponentListener
ContainerAdapter
ContainerListener
FocusAdapter
FocusListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter
MouseMotiuonListener
WindowAdapter
WindowListener


 BEST OF LUCK