Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

module4java (1)

Uploaded by

santhoshr6754
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

module4java (1)

Uploaded by

santhoshr6754
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Delegation Event Model in Java

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.

Event Processing in Java


Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the
AWT was based on inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or handleEvent() methods. The below
image demonstrates the event processing.

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.

Basically, an Event Model is based on the following three components:

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:

1. public void addTypeListener (TypeListener e1)


From the above syntax, the Type is the name of the event, and e1 is a reference to the
event listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all
the events will be notified to registered listeners and receive the event object. This process
is known as event multicasting. In few cases, the event notification will only be sent to
listeners that register to receive them.

Some listeners allow only one listener to register. Below is an example:


1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersExce
ption
From the above syntax, the Type is the name of the event, and e2 is the event listener's
reference. When the specified event occurs, it will be notified to the registered listener. This
process is known as unicasting events.

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.

1. public void removeTypeListener(TypeListener e2?)


From the above syntax, the Type is an event name, and e2 is the reference of the listener.
For example, to remove the keyboard listener, the removeKeyListener() method will be
called.

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:

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.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new delegation-
based event model using AWT to resolve the event problems. It provides a convenient
mechanism to support complex Java programs.

Design Goals
The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.
Let's implement it with an example:

Java Program to Implement the Event Deligation Model


The below is a Java program to handle events implementing the event deligation model:

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

***Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter classes with their corresponding
listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener intListener interfaceerface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Listener interfaceListener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Listener inteListener interfaceerface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example

In the following example, we are implementing the WindowAdapter class of AWT and one its methods windowClosing() to close the frame window.

AdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. public class AdapterExample {
6. // object of Frame
7. Frame f;
8. // class constructor
9. AdapterExample() {
10. // creating a frame with the title
11. f = new Frame ("Window Adapter");
12. // adding the WindowListener to the frame
13. // overriding the windowClosing() method
14. f.addWindowListener (new WindowAdapter() {
15. public void windowClosing (WindowEvent e) {
16. f.dispose();
17. }
18. });
19. // setting the size, layout and
20. f.setSize (400, 400);
21. f.setLayout (null);
22. f.setVisible (true);
23. }
24.
25. // main method
26. public static void main(String[] args) {
27. new AdapterExample();
28. }
29. }
Output:

Java MouseAdapter Example

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

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. // class which inherits the MouseAdapter class
6. public class MouseAdapterExample extends MouseAdapter {
7. // object of Frame class
8. Frame f;
9. // class constructor
10. MouseAdapterExample() {
11. // creating the frame with the title
12. f = new Frame ("Mouse Adapter");
13. // adding MouseListener to the Frame
14. f.addMouseListener(this);
15. // setting the size, layout and visibility of the frame
16. f.setSize (300, 300);
17. f.setLayout (null);
18. f.setVisible (true);
19. }
20. // overriding the mouseClicked() method of the MouseAdapter class
21. public void mouseClicked (MouseEvent e) {
22. // creating the Graphics object and fetching them from the Frame object using getGraphics() method
23. Graphics g = f.getGraphics();
24. // setting the color of graphics object
25. g.setColor (Color.BLUE);
26. // setting the shape of graphics object
27. g.fillOval (e.getX(), e.getY(), 30, 30);
28. }
29. // main method
30. public static void main(String[] args) {
31. new MouseAdapterExample();
32. }
33. }

Output:

Java MouseMotionAdapter Example

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

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits the MouseMotionAdapter class
5. public class MouseMotionAdapterExample extends MouseMotionAdapter {
6. // object of Frame class
7. Frame f;
8. // class constructor
9. MouseMotionAdapterExample() {
10. // creating the frame with the title
11. f = new Frame ("Mouse Motion Adapter");
12. // adding MouseMotionListener to the Frame
13. f.addMouseMotionListener (this);
14. // setting the size, layout and visibility of the frame
15. f.setSize (300, 300);
16. f.setLayout (null);
17. f.setVisible (true);
18. }
19. // overriding the mouseDragged() method
20. public void mouseDragged (MouseEvent e) {
21. // creating the Graphics object and fetching them from the Frame object using getGraphics() method
22. Graphics g = f.getGraphics();
23. // setting the color of graphics object
24. g.setColor (Color.ORANGE);
25. // setting the shape of graphics object
26. g.fillOval (e.getX(), e.getY(), 20, 20);
27. }
28. public static void main(String[] args) {
29. new MouseMotionAdapterExample();
30. }
31. }
Output:

Java KeyAdapter Example

In the following example, we are implementing the KeyAdapter class and its method.

KeyAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits the KeyAdapter class
5. public class KeyAdapterExample extends KeyAdapter {
6. // creating objects of Label, TextArea and Frame
7. Label l;
8. TextArea area;
9. Frame f;
10. // class constructor
11. KeyAdapterExample() {
12. // creating the Frame with title
13. f = new Frame ("Key Adapter");
14. // creating the Label
15. l = new Label();
16. // setting the location of label
17. l.setBounds (20, 50, 200, 20);
18. // creating the text area
19. area = new TextArea();
20. // setting the location of text area
21. area.setBounds (20, 80, 300, 300);
22. // adding KeyListener to text area
23. area.addKeyListener(this);
24. // adding the label and text area to frame
25. f.add(l);
26. f.add(area);
27. // setting the size, layout and visibility of frame
28. f.setSize (400, 400);
29. f.setLayout (null);
30. f.setVisible (true);
31. }
32. // overriding the keyReleased() method
33. public void keyReleased (KeyEvent e) {
34. // creating the String object to get the text fromTextArea
35. String text = area.getText();
36. // splitting the String into words
37. String words[] = text.split ("\\s");
38. // setting the label text to print the number of words and characters of given string
39. l.setText ("Words: " + words.length + " Characters:" + text.length());
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyAdapterExample();
44. }
45. }
Output:

Why AWT is platform independent?

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.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Components

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:

There are four types of containers in Java AWT:

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.

Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

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.

Changes the visibility of the component, by default


public void setVisible(boolean status)
false.

Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

AWT Example by Inheritance

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

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // extending Frame class to our class AWTExample1
5. public class AWTExample1 extends Frame {
6.
7. // initializing using constructor
8. AWTExample1() {
9.
10. // creating a button
11. Button b = new Button("Click Me!!");
12.
13. // setting button position on screen
14. b.setBounds(30,100,80,30);
15.
16. // adding button into frame
17. add(b);
18.
19. // frame size 300 width and 300 height
20. setSize(300,300);
21.
22. // setting the title of Frame
23. setTitle("This is our basic AWT example");
24.
25. // no layout manager
26. setLayout(null);
27.
28. // now frame will be visible, by default it is not visible
29. setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[]) {
34.
35. // creating instance of Frame class
36. AWTExample1 f = new AWTExample1();
37.
38. }
39.
40. }

Output:

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows
and columns.

It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends the Component class.

AWT Scrollbar Class Declaration

1. public class Scrollbar extends Component implements Adjustable, Accessible


Scrollbar Class Fields

The fields of java.awt.Image class are as follows:

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.


o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Scrollbar Class Constructors

Sr. no. Constructor Description

Constructs a new vertical scroll


1 Scrollbar()
bar.

Constructs a new scroll bar with


2 Scrollbar(int orientation)
the specified orientation.

Constructs a new scroll bar with


Scrollbar(int orientation, int
the specified orientation, initial
3 value, int visible, int minimum, int
value, visible amount, and
maximum)
minimum and maximum values.

Where the parameters,

o orientation: specifiey whether the scrollbar will be horizontal or vertical.


o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is moving.
o Maximum: specify the maximum width of track on which scrollbar is moving.

Method Inherited by Scrollbar

The methods of Scrollbar class are inherited from the following classes:

o java.awt.Component
o java.lang.Object

Scrollbar Class Methods

Sr. no. Method name Description

It adds the given adjustment


void addAdjustmentListener listener to receive instances of
1.
(AdjustmentListener l) AdjustmentEvent from the scroll
bar.

2. void addNotify() It creates the peer of scroll bar.

It gets the block increment of


3. int getBlockIncrement()
the scroll bar.

It gets the maximum value of


4. int getMaximum()
the scroll bar.
It gets the minimum value of the
5. int getMinimum()
scroll bar.

It returns the orientation of


6. int getOrientation()
scroll bar.

It fetches the unit increment of


7. int getUnitIncrement()
the scroll bar.

It fetches the current value of


8. int getValue()
scroll bar.

It fetches the visible amount of


9. int getVisibleAmount()
scroll bar.

It returns true if the value is in


process of changing where
10. boolean getValueIsAdjusting()
action results are being taken
by the user.

It returns a string representing


11. protected String paramString()
the state of Scroll bar.

It processes the adjustment


protected void event occurring on scroll bar by
12. processAdjustmentEvent dispatching them to any
(AdjustmentEvent e) registered AdjustmentListener
objects.

protected void It processes the events on the


13.
processEvent(AWTEvent e) scroll bar.

It removes the given adjustment


listener. Thus it no longer
void removeAdjustmentListener
14. receives the instances of
(AdjustmentListener l)
AdjustmentEvent from the scroll
bar.

It sets the block increment from


15. void setBlockIncrement(int v)
scroll bar.

void setMaximum (int It sets the maximum value of


16.
newMaximum) the scroll bar.

It sets the minimum value of the


17. void setMinimum (int newMinimum)
scroll bar.

It sets the orientation for the


18. void setOrientation (int orientation)
scroll bar.

It sets the unit increment for the


19. void setUnitIncrement(int v)
scroll bar.

It sets the value of scroll bar


20. void setValue (int newValue)
with the given argument value.
void setValueIsAdjusting (boolean It sets the valueIsAdjusting
21.
b) property to scroll bar.

It sets the values of four


void setValues (int value, int visible, properties for scroll bar: value,
22.
int minimum, int maximum) visible amount, minimum and
maximum.

void setVisibleAmount (int It sets the visible amount of the


23.
newAmount) scroll bar.

AccessibleContext It gets the accessible context


24.
getAccessibleContext() related to the scroll bar.

It returns an array of al lthe


AdjustmentListener[]
25. adjustment listeners registered
getAdjustmentListeners()
on the scroll bar.

It returns an array if all objects


that are registered as
26. T[] getListeners(ClasslistenerType)
FooListeners on the scroll bar
currently.

Java AWT Scrollbar Example

In the following example, we are creating a scrollbar using the Scrollbar() and adding it into the Frame.

ScrollbarExample1.java

1. // importing awt package


2. import java.awt.*;
3.
4. public class ScrollbarExample1 {
5.
6. // class constructor
7. ScrollbarExample1() {
8.
9. // creating a frame
10. Frame f = new Frame("Scrollbar Example");
11. // creating a scroll bar
12. Scrollbar s = new Scrollbar();
13.
14. // setting the position of scroll bar
15. s.setBounds (100, 100, 50, 100);
16.
17. // adding scroll bar to the frame
18. f.add(s);
19.
20. // setting size, layout and visibility of frame
21. f.setSize(400, 400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25.
26. // main method
27. public static void main(String args[]) {
28. new ScrollbarExample1();
29. }
30. }
Output:
Java AWT Scrollbar Example with AdjustmentListener

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

1. // importing necessary packages


2. import java.awt.*;
3. import java.awt.event.*;
4.
5.
6. public class ScrollbarExample2 {
7.
8. // class constructor
9. ScrollbarExample2() {
10. // creating a Frame with a title
11. Frame f = new Frame("Scrollbar Example");
12.
13. // creating a final object of Label
14. final Label label = new Label();
15.
16. // setting alignment and size of label object
17. label.setAlignment(Label.CENTER);
18. label.setSize(400, 100);
19.
20. // creating a final object of Scrollbar class
21. final Scrollbar s = new Scrollbar();
22.
23. // setting the position of scroll bar
24. s.setBounds(100, 100, 50, 100);
25.
26. // adding Scrollbar and Label to the Frame
27. f.add(s);
28. f.add(label);
29.
30. // setting the size, layout, and visibility of frame
31. f.setSize(400, 400);
32. f.setLayout(null);
33. f.setVisible(true);
34.
35. // adding AdjustmentListener to the scrollbar object
36. s.addAdjustmentListener(new AdjustmentListener() {
37. public void adjustmentValueChanged(AdjustmentEvent e) {
38. label.setText("Vertical Scrollbar value is:"+ s.getValue());
39. }
40. });
41. }
42.
43. // main method
44. public static void main(String args[]){
45. new ScrollbarExample2();
46. }
47. }
Output:

**Java AWT Canvas


The Canvas class controls and represents a blank rectangular area where the application can draw or trap input events from the user. It inherits
the Component class.

AWT Canvas class Declaration

1. public class Canvas extends Component implements Accessible

Canvas Class Constructors

1. Canvas() It constructs a new Canvas.

It constructs a new Canvas with


Canvas(GraphicConfiguration
2. the given Graphic Configuration
config)
object.

Class methods
Sr. no. Method name Description

1. void addNotify() It creates the canvas's peer.

It creates a new multi buffering


void createBufferStrategy (int
2. strategies on the particular
numBuffers)
component.

It creates a new multi buffering


void createBufferStrategy (int
strategies on the particular
3. numBuffers, BufferCapabilities
component with the given buffer
caps)
capabilities.

AccessibleContext It gets the accessible context


4.
getAccessibleContext() related to the Canvas.

It returns the buffer strategy


BufferStrategy
5. used by the particular
getBufferStrategy()
component.

It paints the canvas with given


6. void paint(Graphics g)
Graphics object.

It updates the canvas with given


7. void pdate(Graphics g)
Graphics object.

Method Inherited by Canvas Class

The Canvas has inherited above methods from the following classes:

o lang.Component
o lang.Object

****Java AWT Canvas Example

In the following example, we are creating a Canvas in the Frame and painting a red colored oval inside it.

CanvasExample.java

1. // importing awt class


2. import java.awt.*;
3.
4. // class to construct a frame and containing main method
5. public class CanvasExample
6. {
7. // class constructor
8. public CanvasExample()
9. {
10.
11. // creating a frame
12. Frame f = new Frame("Canvas Example");
13. // adding canvas to frame
14. f.add(new MyCanvas());
15.
16. // setting layout, size and visibility of frame
17. f.setLayout(null);
18. f.setSize(400, 400);
19. f.setVisible(true);
20. }
21.
22. // main method
23. public static void main(String args[])
24. {
25. new CanvasExample();
26. }
27. }
28.
29. // class which inherits the Canvas class
30. // to create Canvas
31. class MyCanvas extends Canvas
32. {
33. // class constructor
34. public MyCanvas() {
35. setBackground (Color.GRAY);
36. setSize(300, 200);
37. }
38.
39. // paint() method to draw inside the canvas
40. public void paint(Graphics g)
41. {
42.
43. // adding specifications
44. g.setColor(Color.red);
45. g.fillOval(75, 75, 150, 75);
46. }
47. }
Output:

***Types of Layout Manager in Java


In Java, graphical user interfaces (GUIs) play a vital role in creating interactive applications. To design a visually appealing and organized interface, the choice of
layout manager becomes crucial. Layout managers define how components are arranged within a container, such as a JFrame or JPanel. Java provides several layout
managers to suit various design needs. In this section, we will delve into the details of the different types of layout managers available in Java, along with code
examples and explanations.

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.

You might also like