module4java (1)
module4java (1)
The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts with
the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a
code to respond to functionality to the user. This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.
But, the modern approach for event processing is based on the Delegation Model. It defines
a standard and compatible mechanism to generate and process events. In this model, a
source generates an event and forwards it to one or more listeners. The listener waits until it
receives an event. Once it receives the event, it is processed by the listener and returns it.
The UI elements are able to delegate the processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.
In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them. So, this approach is more convenient than the inheritance-based event model (in
Java 1.0).
In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took
lots of time. The Delegation Event model overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated
as a reaction of a user while interacting with GUI elements. Some of the event generation
activities are moving the mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many other user operations
as events.
The Events may also occur that may be not related to user interaction, such as a timer
expires, counter exceeded, system failures, or a task is completed, etc. We can define
events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several
different types of events.
A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:
A source should contain a method that unregisters a specific type of event from the listener
if not needed. Below is an example of the method that will remove the event from the
listener.
The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of
events, such as adding or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require
two things; first, it must be registered with a source; however, it can be registered with
several resources to receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces
can be found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse
is dragged and moved. Any object can receive and process these events if it implements
the MouseMotionListener interface.
Types of Events
The events are categories into the following two categories:
The foreground events are those events that require direct interaction of the user. These
types of events are generated as a result of user interaction with the GUI component. For
example, clicking on a button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.
The Background Events :
The Background events are those events that result from the interaction of the end-user.
For example, an Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over
the events and responses.
Design Goals
The design goals of the event delegation model are as following:
TestApp.java:
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18. }
19.
20. class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
49. Command searchCmd = new Command(Command.SEARCH, app);
50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }
Output:
Searching...
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
In the following example, we are implementing the WindowAdapter class of AWT and one its methods windowClosing() to close the frame window.
AdapterExample.java
In the following example, we are implementing the MouseAdapter class. The MouseListener interface is added into the frame to listen the mouse event
in the frame.
MouseAdapterExample.java
Output:
In the following example, we are implementing the MouseMotionAdapter class and its different methods to listen to the mouse motion events in the
Frame window.
MouseMotionAdapterExample.java
In the following example, we are implementing the KeyAdapter class and its method.
KeyAdapterExample.java
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox,
button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows,
MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine
that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS.
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container
class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a container inside container.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. We need to
create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other components like button, text field, scrollbar etc.
Frame is most widely used container while developing an AWT application.
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.
AWTExample1.java
Output:
It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends the Component class.
The methods of Scrollbar class are inherited from the following classes:
o java.awt.Component
o java.lang.Object
In the following example, we are creating a scrollbar using the Scrollbar() and adding it into the Frame.
ScrollbarExample1.java
In the following example, we are creating a Scrollbar and adding it into the Frame. Here, we are using addAdjustmentListener() method of Scrollbar
class which receives the instances of AdjustmentEvent and eventually we display it in the form of Label.
ScrollbarExample2.java
Class methods
Sr. no. Method name Description
The Canvas has inherited above methods from the following classes:
o lang.Component
o lang.Object
In the following example, we are creating a Canvas in the Frame and painting a red colored oval inside it.
CanvasExample.java
1. FlowLayout
FlowLayout is a simple layout manager that arranges components in a row, left to right, wrapping to the next line as needed. It is ideal for scenarios where
components need to maintain their natural sizes and maintain a flow-like structure.
FlowLayoutExample.java
1. import javax.swing.*;
2. import java.awt.*;
3. public class FlowLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("FlowLayout Example");
6. frame.setLayout(new FlowLayout());
7. frame.add(new JButton("Button 1"));
8. frame.add(new JButton("Button 2"));
9. frame.add(new JButton("Button 3"));
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:
2. BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST, and CENTER. Components can be added to these regions, and they will
occupy the available space accordingly. This layout manager is suitable for creating interfaces with distinct sections, such as a title bar, content area, and status bar.
BorderLayoutExample.java
1. import javax.swing.*;
2. import java.awt.*;
3. public class BorderLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("BorderLayout Example");
6. frame.setLayout(new BorderLayout());
7. frame.add(new JButton("North"), BorderLayout.NORTH);
8. frame.add(new JButton("South"), BorderLayout.SOUTH);
9. frame.add(new JButton("East"), BorderLayout.EAST);
10. frame.add(new JButton("West"), BorderLayout.WEST);
11. frame.add(new JButton("Center"), BorderLayout.CENTER);
12. frame.pack();
13. frame.setVisible(true);
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. }
16. }
Output:
3. GridLayout
GridLayout arranges components in a grid with a specified number of rows and columns. Each cell in the grid can hold a component. This layout manager is ideal for
creating a uniform grid of components, such as a calculator or a game board.
GridLayoutExample.java
1. import javax.swing.*;
2. import java.awt.*;
3. public class GridLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridLayout Example");
6. frame.setLayout(new GridLayout(3, 3));
7. for (int i = 1; i <= 9; i++) {
8. frame.add(new JButton("Button " + i));
9. }
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:
4. CardLayout
CardLayout allows components to be stacked on top of each other, like a deck of cards. Only one component is visible at a time, and you can switch between
components using methods like next() and previous(). This layout is useful for creating wizards or multi-step processes.
CardLayoutExample.java
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.ActionEvent;
4. import java.awt.event.ActionListener;
5. public class CardLayoutExample {
6. public static void main(String[] args) {
7. JFrame frame = new JFrame("CardLayout Example");
8. CardLayout cardLayout = new CardLayout();
9. JPanel cardPanel = new JPanel(cardLayout);
10. JButton button1 = new JButton("Card 1");
11. JButton button2 = new JButton("Card 2");
12. JButton button3 = new JButton("Card 3");
13. cardPanel.add(button1, "Card 1");
14. cardPanel.add(button2, "Card 2");
15. cardPanel.add(button3, "Card 3");
16. frame.add(cardPanel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
21. button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
22. button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
23. }
24. }
Output:
5. GroupLayout
GroupLayout is a versatile and complex layout manager that provides precise control over the positioning and sizing of components. It arranges components in a
hierarchical manner using groups. GroupLayout is commonly used in GUI builders like the one in NetBeans IDE.
GroupLayoutExample.java
1. import javax.swing.*;
2. public class GroupLayoutExample {
3. public static void main(String[] args) {
4. JFrame frame = new JFrame("GroupLayout Example");
5. JPanel panel = new JPanel();
6. GroupLayout layout = new GroupLayout(panel);
7. panel.setLayout(layout);
8. JButton button1 = new JButton("Button 1");
9. JButton button2 = new JButton("Button 2");
10. layout.setHorizontalGroup(layout.createSequentialGroup()
11. .addComponent(button1)
12. .addComponent(button2));
13. layout.setVerticalGroup(layout.createParallelGroup()
14. .addComponent(button1)
15. .addComponent(button2));
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. }
Output:
6. GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create complex layouts by specifying constraints for each component. It arranges components in a
grid, but unlike GridLayout, it allows components to span multiple rows and columns and have varying sizes.
GridBagLayoutExample.java
1. import javax.swing.*;
2. import java.awt.*;
3. public class GridBagLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridBagLayout Example");
6. JPanel panel = new JPanel(new GridBagLayout());
7. GridBagConstraints constraints = new GridBagConstraints();
8. constraints.fill = GridBagConstraints.HORIZONTAL;
9. JButton button1 = new JButton("Button 1");
10. JButton button2 = new JButton("Button 2");
11. constraints.gridx = 0;
12. constraints.gridy = 0;
13. panel.add(button1, constraints);
14. constraints.gridx = 1;
15. panel.add(button2, constraints);
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. }
Output:
Conclusion
Java offers a variety of layout managers to cater to different design requirements. By choosing the appropriate layout manager, we can create visually appealing and
organized GUIs that enhance the user experience. Whether we need a linear flow, grid arrangement, region-based distribution, or card-based navigation.