0% found this document useful (0 votes)
81 views5 pages

Unit Vi Event Handling

The document discusses different layout managers in Java including: - FlowLayout (the default), which arranges components sequentially from left to right and top to bottom with spacing between. - BorderLayout, which divides a container into north, south, east, west, and center regions for fixed-width components. - GridLayout, which lays out components in a grid with a specified number of rows and columns. - CardLayout, which stores multiple layouts and allows shuffling between "cards" of different layouts to dynamically show/hide components. - GridBagLayout, which allows specifying component positions and sizes within a flexible grid structure where rows can vary in number of columns.

Uploaded by

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

Unit Vi Event Handling

The document discusses different layout managers in Java including: - FlowLayout (the default), which arranges components sequentially from left to right and top to bottom with spacing between. - BorderLayout, which divides a container into north, south, east, west, and center regions for fixed-width components. - GridLayout, which lays out components in a grid with a specified number of rows and columns. - CardLayout, which stores multiple layouts and allows shuffling between "cards" of different layouts to dynamically show/hide components. - GridBagLayout, which allows specifying component positions and sizes within a flexible grid structure where rows can vary in number of columns.

Uploaded by

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

UNIT VI EVENT HANDLING

UNIT VI EVENT HANDLING


The Delegation Event Model The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the old Java 1. approach.

Events
In the delegation model, an event is an ob!ect that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. "ome of the activities that cause events to be generated are pressing a button, entering a character via the #eyboard, selecting an item in a list, and clic#ing the mouse. $vents may also occur that are not directly caused by interactions with a user interface. %or e&ample, an event may be generated when a timer e&pires, a counter e&ceeds a value, a software or hardware failure occurs, or an operation is completed.

Event Sources
' source is an ob!ect that generates an event. This occurs when the internal state of that ob!ect changes in some way. "ources may generate more than one type of event. ' source must register listeners in order for the listeners to receive notifications about a specific type of event. $ach type of event has its own registration method.(ere is the general form: public void add Type)istener*Type)istener el+ (ere, Type is the name, of the event and el is a reference to the event listener. %or e&ample, the method that registers a #eyboard event listener is called addKe Listener!". The method that registers a mouse motion listener is called addMouseMotionListener!".

Event Listeners#
' listener is an ob!ect that is notified when an event occurs. It has two ma!or requirements. %irst, it must have been registered with one or more sources to receive notifications about specific types of events. "econd, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in $ava%a&t%event. %or e&ample, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. 'ny ob!ect may receive and process one or both of these events if it provides an implementation of this interface.

Event Listener Inter'aces


6.1 Prepared by PHANI KISHORE ROMPICHRLA

UNIT VI EVENT HANDLING

The delegation event model has two parts: sources and listeners. )isteners are created by implementing one or more of the interfaces defined by the $ava%a&t%event pac#age. -hen an event occurs, the event source invo#es the appropriate method defined by the listener and provides an event ob!ect as its argument Ada(ter )lasses Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations. 'n adapter class provides an empty implementation of all methods in an event listener interface. 'dapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. .ou can define a new class to act as an event listener by e&tending one of the adapter classes and implementing only those events in which you are interested. %or e&ample, the MouseMotionAda(ter class has two methods, *ouseDragged! " and *ouseMoved! ". The signatures of these empty methods are e&actly as defined in the MouseMotionListener interface. If you were interested in only mouse drag events, then you could simply e&tend MouseMotionAda(ter and implement *ouseDragged! ". The empty implementation of *ouseMoved! " would handle the mouse motion events for you. Anon *ous Inner )lasses 'n anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner class can facilitate the writing of event handlers. /onsider the applet shown in the following listing. 's before, its goal is to display the string 01ouse 2ressed3 in the status bar of the applet viewer or browser when the mouse is pressed. La out Manager a layout manager automatically arranges your controls within a window by using some type of algorithm.$ach )ontainer ob!ect has a layout manager associated with it. ' layout manager is an instance of any class that implements the La outManager interface. The layout manager is set by the setLa out! " method. If no call to setLa out! " is made, then the default layout manager is used. -henever a container is resi4ed *or si4ed for the first time+, the layout manager is used to position each of the components within it. The setLa out! " method has the following general form: void set)ayout*)ayout1anager layoutObj+ (ere, layoutObj is a reference to the desired layout manager. If you wish to disable the layout manager and position components manually, pass null for layoutObj. If you do this, you will need to determine the shape and position of each component manually,using the set+ounds! " method defined by )o*(onent. 5ormally, you will want to use a layout manager.$ach layout manager #eeps trac# of a list of components that are stored by their names. The layout manager is notified each time you add a component to a container. -henever the container needs to be resi4ed, the layout manager is consulted via its *ini*u*La outSi,e! " and (re'erredLa outSi,e! " methods. $ach component that is being managed by a layout manager contains the get-re'erredSi,e! " and getMini*u*Si,e! " methods.
.L/0LA1/UT#

.lo&La out is the default layout manager. This is the layout manager that the preceding e&amples have used. .lo&La out implements a simple layout style, which is similar to how words flow in a te&t editor./omponents are laid out from the upper6left corner, left to right and top to bottom. -hen no more components fit on a line, the ne&t one appears on the ne&t line. ' small space is left between each component, above and below, as well as left and right. (ere are the constructors for .lo&La out: 6.2 %low)ayout* + Prepared by PHANI KISHORE ROMPICHRLA

UNIT VI EVENT HANDLING

%low)ayout*int how+ %low)ayout*int how, int horz, int vert+


+/2DE2 LA1/UT#

The +orderLa out class implements a common layout style for top6level windows. It has four narrow,fi&ed6width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center. (ere are the constructors defined by +orderLa out: 7order)ayout* + 7order)ayout*int horz, int vert+ The first form creates a default border layout. The second allows you to specify the hori4ontal and vertical space left between components in horz and vert, respectively. +orderLa out defines the following constants that specify the regions: 7order)ayout./$5T$8 7order)ayout."O9T( 7order)ayout.$'"T 7order)ayout.-$"T 7order)ayout.5O8T(
G2ID LA1/UT#

GridLa out lays out components in a two6dimensional grid. -hen you instantiate a GridLa out, you define the number of rows and columns. The constructors supported by GridLa out are shown here: :rid)ayout* + :rid)ayout*int numRows, int numColumns + :rid)ayout*int numRows, int numColumns, int horz, int vert+ The first form creates a single6column grid layout. The second form creates a grid layout with the specified number of rows and columns. The third form allows youto specify the hori4ontal and vertical space left between components in horz and vert, respectively. $ither numRows or numColumns can be 4ero. "pecifying numRows as 4ero allows for unlimited6length columns. "pecifying numColumns as 4ero allows for unlimited6length rows $g: see the e&ample which I was given in running notes
)A2D LA1/UT#

The )ardLa out class is unique among the other layout managers in that it stores several different layouts. $ach layout can be thought of as being on a separate inde& card in a dec# that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. .ou can prepare the other layouts and have them hidden, ready to be activated when needed. )ardLa out provides these two constructors: /ard)ayout* + /ard)ayout*int horz, int vert+ The first form creates a default card layout. The second form allows you to specify the hori4ontal 6.3 Prepared by PHANI KISHORE ROMPICHRLA

UNIT VI EVENT HANDLING

andvertical space left between components in horz and vert, respectively. 9se of a card layout requires a bit more wor# than the other layouts. The cards are typically held in an ob!ect of type -anel. This panel must have )ardLa out selected as its layout manager. The cards that form the dec# are also typically ob!ects of type -anel. Thus, you must create a panel that contains the dec# and a panel for each card in the dec#. 5e&t, you add to the appropriate panel the components that form each card. .ou then add these panels to the panel for which )ardLa out is the layout manager. %inally, you add this panel to the main applet panel.
G2ID+AG LA1/UT#

9sing :rid7ag)ayout class you can specify the relative placement of components by specifying this positions within cells inside a grid. The #ey to :rid7ag is that each component can be a different si4e and each row in the grid can have a different number of columns this is why the layout is called a grid7ag It is a collection of small grids !oined together. The location and si4e of each component in a grid7ag are determined by a set of constraints lin#ed to it. The constraints are contained in an ob!ect of type :rid7ag/onstraints. /onstraints include the height and width of a cell the placement of acomponent and

its alignement.
-ANEL#

The -anel class is a concrete subclass of )ontainer. It doesn;t add any new methods< it simply implements .' -anel may be thought of as a recursively nestable, concrete screen component. -anel is the superclass for A((let. -hen screen output is directed to an applet, it is drawn on the surface of a -anel ob!ect. In essence, a -anel is a window that does not contain a title bar, menu bar, or border. This is why you don;t see these items when an applet is run inside a browser. -hen you run an applet using an applet viewer, the applet viewer provides the title and border. Other components can be added to a -anel ob!ect by its add! " method *inherited from )ontainer+. Once these components have been added, you can position and resi4e them manually using the setLocation! ", setSi,e! ", or set+ounds! " methods defined by component.
)/NTAINE2#

The )ontainer class is a subclass of )o*(onent. It has additional methods that allow other )o*(onent ob!ects to be nested within it. Other )ontainer ob!ects can be stored inside of a )ontainer *since they are themselves instances of )o*(onent+. This ma#es for a multileveled c ontainment system. ' container is responsible for laying out *that is, positioning+ any components that it contains.
0IND/0#

The 0indo& class creates a top6level window. ' top-level window is not contained within any other ob!ect< it sits directly on the des#top. :enerally, you won;t create 0indo& ob!ects directly. Instead, you will use a subclass of 0indo& called .ra*e.
.2AME#

.ra*e encapsulates what is commonly thought of as a 0window.3 It is a subclass of 0indo& and has a title bar, menu bar, borders, and resi4ing corners. If you create a .ra*e ob!ect from within an applet, it will contain a warning message, such as 0Java 'pplet -indow,3 to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer. *'n applet that could masquerade as a host6based application could be used to obtain passwords and other sensitive information without the user;s #nowledge.+ -hen a .ra*e window is created by a program rather than an applet, a normal window is created. 6.4 Prepared by PHANI KISHORE ROMPICHRLA

UNIT VI EVENT HANDLING

)reating a .ra*e 0indo& in an A((let -hile it is possible to simply create a window by creating an instance of .ra*e, you will seldom do so, because you will not be able to do much with it. %or e&ample, you will not be able to receive or process events that occur within it or easily output information to it. 1ost of the time, you will create a subclass of .ra*e. =oing so lets you override .ra*e;s methods and event handling. /reating a new frame window from within an applet is actually quite easy. %irst, create a subclass of .ra*e. 5e&t, override any of the standard window methods, such as init! ", start! ", sto(! ", and (aint! ". %inally, implement the &indo&)losing! " method of the 0indo&Listener interface, calling setVisi3le!'alse" when the window is closed

6.5

Prepared by PHANI KISHORE ROMPICHRLA

Common questions

Powered by AI

Java layout managers like FlowLayout, BorderLayout, and GridLayout provide different strategies to arrange components in a container. FlowLayout arranges components in a simple text-editor-like flow, left to right and top to bottom, wrapping when needed. BorderLayout divides the container into five regions (north, south, east, west, center), allowing components to occupy fixed positions. GridLayout imposes a grid of equally sized cells, with components filling each cell. By using these managers, developers can create responsive and organized GUIs that automatically adjust to various window sizes and ensure components are properly aligned and spaced without manually handling their positions .

The delegation event model divides responsibilities between event sources and event listeners. A source is an object that generates an event due to a change in its state, such as user actions like mouse clicks or key presses. To efficiently manage event handling, sources only send notifications to listeners that have registered interest in specific types of events. This ensures that notifications are only sent to those who need them, optimizing performance. Listeners are objects that have registered with a source to respond to specific events. They implement specific methods to process the event once notified, which separates application logic from the UI and leads to cleaner code. This model is more efficient than the older Java 1.0 event handling model as it avoids unnecessary notifications to uninterested listeners .

To manually control component positions without a layout manager, the setBounds() method defined by the Component class can be used. This allows for explicit setting of component size and location. However, this approach has drawbacks, such as increased complexity and effort required for maintaining the layout across different window sizes or resolutions, potentially leading to poor UI adaptability and responsiveness. Moreover, changes in the UI might require significant redeployment since components do not automatically adjust their positions or sizes .

A layout manager determines the relative sizes and positions of components within a container, and it automatically adjusts these aspects when the container is resized. For example, with a FlowLayout, components will realign themselves in a new flow if the width changes. In a BorderLayout, resizing might affect the distribution of space among regions, but the central component usually resizes to occupy available space. A GridLayout will ensure all cells expand or contract uniformly. Layout managers facilitate adaptive UIs, as they handle component arrangement dynamically without the need for manual intervention, maintaining usability across varying display sizes .

Adapter classes in Java provide empty implementations of all methods in an event listener interface. This allows developers to extend an adapter class and override only the methods that correspond to the events they are interested in. For instance, if a programmer is only concerned with mouse drag events, they can extend the MouseMotionAdapter and implement only the mouseDragged() method. This negates the need to provide empty or unused implementations for other methods, thereby simplifying the event handling process and reducing boilerplate code .

GridBagLayout allows for flexible component positioning by enabling components to have varying sizes and allowing different grid rows to have different numbers of cells. Unlike layouts such as GridLayout, which enforce uniform cell sizes, GridBagLayout uses a constraints object, GridBagConstraints, to specify attributes like cell width, height, and alignment for individual components. This flexibility makes GridBagLayout suited for complex UI designs requiring precise control over component placement and alignment, offering unmatched adaptability in arranging components compared to other layout managers .

In Java GUI applications, the Panel class acts as a basic container within which components can be grouped and organized. Panels don't have titles, borders, or menu bars, making them ideal for internal grouping within larger windows or applets. The Frame class, a subclass of Window, serves as a top-level container typically representing the main window of an application. Frames have a title bar, borders, and can function independently on the desktop. Together, Panel and Frame facilitate a hierarchical structure for organizing and managing components, with Frames offering window-based functionality and Panels allowing for recursive nesting and detailed control of component placement within those windows .

The delegation event model offers several advantages over the older Java 1.0 event model. It provides a clean separation between event production and handling, allowing for more modular and maintainable code. Listeners must register with sources to receive events, meaning notifications are only sent to those interested, increasing efficiency. This contrasts with the Java 1.0 model, where events were handled more globally, often leading to redundant processing by uninterested listeners. Additionally, by adhering to specific interfaces for event listeners, the delegation model simplifies the task of creating consistent and predictable event responses .

The CardLayout manager differs from other layout managers because it allows for multiple layouts to be stored and managed as a deck of cards, with only one displayed at a time. This feature is advantageous for creating dynamic user interfaces where different components or panels need to be shown or hidden based on user interaction. By switching between cards, developers can create interfaces where optional components are accessible without taking up screen space unnecessarily. This dynamic nature is particularly useful for wizard-like interfaces or tabbed views .

Anonymous inner classes allow for the creation of concise and easily readable event handlers directly within the body of a method. Since they do not require a separate named class, they streamline code when handling events that require only short, one-time use implementations. This is particularly useful in GUI programming, where events are often tied closely with specific interface components. By using anonymous inner classes, programmers can directly implement the necessary event listener interface methods in place, keeping related code local and improving the encapsulation of functionality .

You might also like