0% found this document useful (0 votes)
249 views

Java Unit-4

1. The document discusses event handling in Java, including event sources, event classes, event listeners, and the delegation event model. 2. Key aspects of event handling are that event sources generate events that are passed to registered listener objects. Listeners implement interfaces that define methods to handle specific event types. 3. The delegation event model separates the generation of events by sources from the handling of events by listeners. Sources notify listeners of events by invoking listener methods.

Uploaded by

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

Java Unit-4

1. The document discusses event handling in Java, including event sources, event classes, event listeners, and the delegation event model. 2. Key aspects of event handling are that event sources generate events that are passed to registered listener objects. Listeners implement interfaces that define methods to handle specific event types. 3. The delegation event model separates the generation of events by sources from the handling of events by listeners. Sources notify listeners of events by invoking listener methods.

Uploaded by

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

UNIT-4

Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes. The AWT class
hierarchy, user interface components- labels, button, canvas, scrollbars, text
components, check box, checkbox groups, choices, lists panels – scrollpane, dialogs,
menubar, graphics, layout manager – layout manager types – border,grid, flow, card
and grid bag.

Event Handling

Events
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion,
etc.

Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
An event handler is a function or method that executes program statements in response to
an event. A software program that processes activities such as keystrokes and mouse
movements is what an event handler is. Event handlers in Web sites make Web content
dynamic.

Delegation Event model


How delegation event model works:

The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. 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 an event is
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.
A user interface element is able to ―delegate‖ the processing of an event to a
separate piece of code. 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.

• It has Event Sources and Event Listeners.

Delegation Event Model

Event Source:
• Events are generated from the source(components). There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
• An object on which an event occurs is referred to as a source. The source is in
charge of informing the handler about the event that occurred. There are various
sources like buttons, checkboxes, lists, menu-item, choices, scrollbars, text
components, windows, etc.
Event Listeners:
• Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
• When an event occurs, an object named an event listener is called. The listeners
need two things: first, they must be registered with a source; however, they can
be registered with multiple sources to receive event notifications.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes and Listeners in Java


Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred
ActionEvent ActionListener
like a button click or selecting an item
from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size changed or
changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a container
object.

These are focus-related events, which


FocusEvent FocusListener include focus, focusin, focusout, and
blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a sequence


KeyEvent KeyListener
of keypresses on the keyboard.
Event Class Listener Interface Description

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.

Different interfaces consist of different methods which are specified below.

Listener Interface Methods

ActionListener • actionPerformed()

AdjustmentListener • adjustmentValueChanged()

• componentResized()
• componentShown()
ComponentListener
• componentMoved()
• componentHidden()

• componentAdded()
ContainerListener
• componentRemoved()

• focusGained()
FocusListener
• focusLost()

ItemListener • itemStateChanged()

• keyTyped()
KeyListener • keyPressed()
• keyReleased()
Listener Interface Methods

• mousePressed()
• mouseClicked()
MouseListener • mouseEntered()
• mouseExited()
• mouseReleased()

• mouseMoved()
MouseMotionListener
• mouseDragged()

MouseWheelListener • mouseWheelMoved()

TextListener • textChanged()

• windowActivated()
• windowDeactivated()
• windowOpened()
WindowListener • windowClosed()
• windowClosing()
• windowIconified()
• windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Example 1:
// Java program to demonstrate the
// event handling within the class

import java.awt.*;
import java.awt.event.*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}
Output
Handling Mouse And Keyboard Events

Java MouseListener Interface

The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has
five methods.

Methods of MouseListener interface

The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }

Output:

Java KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has
three methods.

Following is the declaration for java.awt.event.KeyListener interface:

1. public interface KeyListener extends EventListener

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:


Sr. no. Method name Description

1. public abstract void keyPressed It is invoked when a key has been


(KeyEvent e); pressed.

2. public abstract void keyReleased It is invoked when a key has been


(KeyEvent e); released.

3. public abstract void keyTyped (KeyEvent It is invoked when a key has been
e); typed.

Methods inherited

This interface inherits methods from the following interface:

java.awt.EventListener

In the following example, we are implementing the methods of the KeyListener interface.

KeyListenerExample.java

1. import java.awt.*; // importing awt libraries


2. import java.awt.event.*;
3. // class which inherits Frame class and implements KeyListener interface
4. public class KeyListenerExample extends Frame implements KeyListener {
5. // creating object of Label class and TextArea class
6. Label l;
7. TextArea area;
8. // class constructor
9. KeyListenerExample() {
10. // creating the label
11. l = new Label();
12. // setting the location of the label in frame
13. l.setBounds (20, 50, 100, 20);
14. // creating the text area
15. area = new TextArea();
16. // setting the location of text area
17. area.setBounds (20, 80, 300, 300);
18. // adding the KeyListener to the text area
19. area.addKeyListener(this);
20. // adding the label and text area to the frame
21. add(l);
22. add(area);
23. // setting the size, layout and visibility of frame
24. setSize (400, 400);
25. setLayout (null);
26. setVisible (true);
27. }
28. // overriding the keyPressed() method of KeyListener interface where we set the text o
f the label when key is pressed
29. public void keyPressed (KeyEvent e) {
30. l.setText ("Key Pressed");
31. }
32. // overriding the keyReleased() method of KeyListener interface where we set the text
of the label when key is released
33. public void keyReleased (KeyEvent e) {
34. l.setText ("Key Released");
35. }
36. // overriding the keyTyped() method of KeyListener interface where we set the text of
the label when a key is typed
37. public void keyTyped (KeyEvent e) {
38. l.setText ("Key Typed");
39. }
40. // main method
41. public static void main(String[] args) {
42. new KeyListenerExample();
43. }
44. }
Output:
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 interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

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

AWT Class Hierarchy

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.

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.

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

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 Sets the size (width and height) of the component.
height)

public void setLayout(LayoutManager Defines the layout manager for the component.
m)

public void setVisible(boolean status) Changes the visibility of the component, by default
false.

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. // extending Frame class to our class AWTExample1
4. public class AWTExample1 extends Frame {
5. // initializing using constructor
6. AWTExample1() {
7. // creating a button
8. Button b = new Button("Click Me!!");
9. // setting button position on screen
10. b.setBounds(30,100,80,30);
11. // adding button into frame
12. add(b);
13. // frame size 300 width and 300 height
14. setSize(300,300);
15. // setting the title of Frame
16. setTitle("This is our basic AWT example");
17. // no layout manager
18. setLayout(null);
19. // now frame will be visible, by default it is not visible
20. setVisible(true);
21. }
22. // main method
23. public static void main(String args[]) {
24. // creating instance of Frame class
25. AWTExample1 f = new AWTExample1();
26. }
27. }
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above
example that sets the position of the awt button.
Output:
AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.

1. // importing Java AWT class


2. import java.awt.*;
3. // class AWTExample2 directly creates instance of Frame class
4. class AWTExample2 {
5. // initializing using constructor
6. AWTExample2() {
7. // creating a Frame
8. Frame f = new Frame();
9. // creating a Label
10. Label l = new Label("Employee id:");
11. // creating a Button
12. Button b = new Button("Submit");
13. // creating a TextField
14. TextField t = new TextField();
15. // setting position of above components in the frame
16. l.setBounds(20, 80, 80, 30);
17. t.setBounds(20, 100, 80, 30);
18. b.setBounds(100, 100, 80, 30);
19. // adding components into frame
20. f.add(b);
21. f.add(l);
22. f.add(t);
23. // frame size 300 width and 300 height
24. f.setSize(400,300);
25. // setting the title of frame
26. f.setTitle("Employee info");
27. // no layout
28. f.setLayout(null);
29. // setting visibility of frame
30. f.setVisible(true);
31. }
32. // main method
33. public static void main(String args[]) {
34. // creating instance of Frame class
35. AWTExample2 awt_obj = new AWTExample2();
36. }
37. }
Output:

User Interface Components-


Java AWT Label

The object of the Label 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 a programmer but a user
cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a
label, we need to create the object of Label class.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible
AWT Label Fields

The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors


Sr. Constructor Description
no.

1. Label() It constructs an empty label.

2. Label(String text) It constructs a label with the given string (left justified
by default).

3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.

Label Class Methods


Sr. no. Method name Description

1. void setText(String text) It sets the texts for label with the specified text.

2. void setAlignment(int alignment) It sets the alignment for label with the specified
alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

5. void addNotify() It creates the peer for the label.

6. AccessibleContext It gets the Accessible Context associated with


getAccessibleContext() the label.

7. protected String paramString() It returns the string the state of the label.

Java AWT Label Example

In the following example, we are creating two labels l1 and l2 using the Label(String text)
constructor and adding them into the frame.

LabelExample.java

1. import java.awt.*;
2. public class LabelExample {
3. public static void main(String args[]){
4. // creating the object of Frame class and Label class
5. Frame f = new Frame ("Label example");
6. Label l1, l2;
7. // initializing the labels
8. l1 = new Label ("First Label.");
9. l2 = new Label ("Second Label.");
10. // set the location of label
11. l1.setBounds(50, 100, 100, 30);
12. l2.setBounds(50, 150, 100, 30);
13. // adding labels to the frame
14. f.add(l1);
15. f.add(l2);
16. // setting size, layout and visibility of frame
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }

Output:

Java AWT Button

A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives the
all the events, then it passes an action event by calling its own method processActionEvent.
This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.

AWT Button Class Declaration


1. public class Button extends Component implements Accessible

Button Class Constructors

Following table shows the types of Button class constructors

Sr. no. Constructor Description

1. Button( ) It constructs a new button with an empty string i.e. it has no


label.

2. Button (String It constructs a new button with given string as its label.
text)

Button Class Methods


Sr. Method Description
no.

1. void setText (String text) It sets the string message on the button

2. String getText() It fetches the String message on the button.

3. void setLabel (String label) It sets the label of button with the specified string.

4. String getLabel() It fetches the label of the button.

5. void addNotify() It creates the peer of the button.

6. AccessibleContext It fetched the accessible context associated with


getAccessibleContext() the button.

7. void It adds the specified action listener to get the


addActionListener(ActionListener action events from the button.
l)

8. String getActionCommand() It returns the command name of the action event


fired by the button.

9. ActionListener[ ] It returns an array of all the action listeners


getActionListeners() registered on the button.

10. T[ ] It returns an array of all the objects currently


getListeners(Class listenerType) registered as FooListeners upon this Button.

11. protected String paramString() It returns the string which represents the state of
button.

12. protected void It process the action events on the button by


processActionEvent (ActionEvent dispatching them to a registered ActionListener
e) object.

13. protected void processEvent It process the events on the button


(AWTEvent e)

14. void removeActionListener It removes the specified action listener so that it no


(ActionListener l) longer receives action events from the button.

15. void setActionCommand(String It sets the command name for the action event
command) given by the button.

Note: The Button class inherits methods from java.awt.Component and java.lang.Object
classes.
Java AWT Button Example

ButtonExample.java

1. import java.awt.*;
2. public class ButtonExample {
3. public static void main (String[] args) {
4. // create instance of frame with the label
5. Frame f = new Frame("Button Example");
6. // create instance of button with label
7. Button b = new Button("Click Here");
8. // set the position for the button in frame
9. b.setBounds(50,100,80,30);
10. // add button to the frame
11. f.add(b);
12. // set size, layout and visibility of frame
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

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


Sr. Constructor Description
no.

1. Canvas() It constructs a new Canvas.


2. Canvas(GraphicConfiguration It constructs a new Canvas with the given Graphic
config) Configuration object.

Class methods
Sr. Method name Description
no.

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

2. void createBufferStrategy (int It creates a new multi buffering strategies on the


numBuffers) particular component.

3. void createBufferStrategy (int It creates a new multi buffering strategies on the


numBuffers, BufferCapabilities particular component with the given buffer
caps) capabilities.

4. AccessibleContext It gets the accessible context related to the


getAccessibleContext() Canvas.

5. BufferStrategy It returns the buffer strategy used by the


getBufferStrategy() particular component.

6. void paint(Graphics g) It paints the canvas with given Graphics object.

7. void pdate(Graphics g) It updates the canvas with given Graphics 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. // class to construct a frame and containing main method
4. public class CanvasExample
5. {
6. // class constructor
7. public CanvasExample()
8. {
9. // creating a frame
10. Frame f = new Frame("Canvas Example");
11. // adding canvas to frame
12. f.add(new MyCanvas());
13. // setting layout, size and visibility of frame
14. f.setLayout(null);
15. f.setSize(400, 400);
16. f.setVisible(true);
17. }
18. // main method
19. public static void main(String args[])
20. {
21. new CanvasExample();
22. }
23. }
24. // class which inherits the Canvas class to create Canvas
25. class MyCanvas extends Canvas
26. {
27. // class constructor
28. public MyCanvas() {
29. setBackground (Color.GRAY);
30. setSize(300, 200);
31. }
32. // paint() method to draw inside the canvas
33. public void paint(Graphics g)
34. {
35. // adding specifications
36. g.setColor(Color.red);
37. g.fillOval(75, 75, 150, 75);
38. }
39. }
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


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. Constructor Description
no.

1 Scrollbar() Constructs a new vertical scroll bar.

2 Scrollbar(int orientation) Constructs a new scroll bar with the specified


orientation.

3 Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, orientation, initial value, visible amount, and
int 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.

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. public class ScrollbarExample1 {
4. // class constructor
5. ScrollbarExample1() {
6. // creating a frame
7. Frame f = new Frame("Scrollbar Example");
8. // creating a scroll bar
9. Scrollbar s = new Scrollbar();
10. // setting the position of scroll bar
11. s.setBounds (100, 100, 50, 100);
12. // adding scroll bar to the frame
13. f.add(s);
14. // setting size, layout and visibility of frame
15. f.setSize(400, 400);
16. f.setLayout(null);
17. f.setVisible(true);
18. }
19. // main method
20. public static void main(String args[]) {
21. new ScrollbarExample1();
22. }
23. }
Output:

Java AWT TextField or Text Compnent

The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed), the event
is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also
be done using ActionEvent; if the ActionEvent is enabled on the text field, then the
ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.

AWT TextField Class Declaration


1. public class TextField extends TextComponent

TextField Class constructors

Sr. Constructor Description


no.

1. TextField() It constructs a new text field component.

2. TextField(String text) It constructs a new text field initialized with the given
string text to be displayed.

3. TextField(int columns) It constructs a new textfield (empty) with given number of


columns.

4. TextField(String text, It constructs a new text field with the given text and given
int columns) number of columns (width).

Java AWT TextField Example

TextFieldExample1.java

1. // importing AWT class


2. import java.awt.*;
3. public class TextFieldExample1 {
4. // main method
5. public static void main(String args[]) {
6. // creating a frame
7. Frame f = new Frame("TextField Example");
8. // creating objects of textfield
9. TextField t1, t2;
10. // instantiating the textfield objects
11. // setting the location of those objects in the frame
12. t1 = new TextField("Welcome to Javatpoint.");
13. t1.setBounds(50, 100, 200, 30);
14. t2 = new TextField("AWT Tutorial");
15. t2.setBounds(50, 150, 200, 30);
16. // adding the components to frame
17. f.add(t1);
18. f.add(t2);
19. // setting size, layout and visibility of frame
20. f.setSize(400,400);
21. f.setLayout(null);
22. f.setVisible(true);
23. }
24. }
Output:

Java AWT Checkbox

The Checkbox 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".

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
Sr. Constructor Description
no.

1. Checkbox() It constructs a checkbox with no string as the label.

2. Checkbox(String label) It constructs a checkbox with the given label.

3. Checkbox(String label, boolean It constructs a checkbox with the given label and
state) sets the given state.

4. Checkbox(String label, boolean It constructs a checkbox with the given label, set
state, CheckboxGroup group) the given state in the specified checkbox group.

5. Checkbox(String label, It constructs a checkbox with the given label, in the


CheckboxGroup group, boolean given checkbox group and set to the specified state.
state)
In the following example we are creating two checkboxes using the Checkbox(String label)
constructor and adding them into the Frame using add() method.

CheckboxExample1.java

1. // importing AWT class


2. import java.awt.*;
3. public class CheckboxExample1
4. {
5. // constructor to initialize
6. CheckboxExample1() {
7. // creating the frame with the title
8. Frame f = new Frame("Checkbox Example");
9. // creating the checkboxes
10. Checkbox checkbox1 = new Checkbox("C++");
11. checkbox1.setBounds(100, 100, 50, 50);
12. Checkbox checkbox2 = new Checkbox("Java", true);
13. // setting location of checkbox in frame
14. checkbox2.setBounds(100, 150, 50, 50);
15. // adding checkboxes to frame
16. f.add(checkbox1);
17. f.add(checkbox2);
18. // setting size, layout and visibility of frame
19. f.setSize(400,400);
20. f.setLayout(null);
21. f.setVisible(true);
22. }
23. // main method
24. public static void main (String args[])
25. {
26. new CheckboxExample1();
27. }
28. }
Output:

Java AWT Choice

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

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible
Choice Class constructor
Sr. no. Constructor Description

1. Choice() It constructs a new choice menu.

In the following example, we are creating a choice menu using Choice() constructor. Then we
add 5 items to the menu using add() method and Then add the choice menu into the Frame.

ChoiceExample1.java

1. // importing awt class


2. import java.awt.*;
3. public class ChoiceExample1 {
4. // class constructor
5. ChoiceExample1() {
6. // creating a frame
7. Frame f = new Frame();
8. // creating a choice component
9. Choice c = new Choice();
10. // setting the bounds of choice menu
11. c.setBounds(100, 100, 75, 75);
12. // adding items to the choice menu
13. c.add("Item 1");
14. c.add("Item 2");
15. c.add("Item 3");
16. c.add("Item 4");
17. c.add("Item 5");
18. // adding choice menu to frame
19. f.add(c);
20. // setting size, layout and visibility of frame
21. f.setSize(400, 400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. // main method
26. public static void main(String args[])
27. {
28. new ChoiceExample1();
29. }
30. }

Output:

Java AWT Dialog

The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.

Unlike Frame, it doesn't have maximize and minimize buttons.


Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.

AWT Dialog class declaration


1. public class Dialog extends Window
Java AWT Dialog Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }
Output:

Java AWT MenuItem and Menu

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

The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.

AWT MenuItem class declaration


1. public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
1. public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT MenuItem and Menu Example
1. import java.awt.*;
2. class MenuExample
3. {
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. menu.add(i1);
15. menu.add(i2);
16. menu.add(i3);
17. submenu.add(i4);
18. submenu.add(i5);
19. menu.add(submenu);
20. mb.add(menu);
21. f.setMenuBar(mb);
22. f.setSize(400,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public static void main(String args[])
27. {
28. new MenuExample();
29. }
30. }
Output:

Graphics in Applet
The Graphics class, located within the java.awt package, is an abstract superclass that
provides a unified interface for drawing shapes, text, and images onto the screen. It
encapsulates the basic drawing operations that every device must support, enabling Java
applications to render 2D graphics in a platform-independent manner.

java.awt.Graphics class provides many methods for graphics programming.

The Graphics class provides a suite of methods for drawing shapes, filling shapes, managing
color and font settings, and more. Here are some of its most important methods :−

• public abstract void drawString(String str, int x, int y) − This method is used to
draw a specified string at the specified location (x, y).
• public void drawRect(int x, int y, int width, int height) − This method draws a
rectangle from the point (x, y) with the specified width and height
• public abstract void fillRect(int x, int y, int width, int height) − This method is
used to fill a rectangle from the point (x, y) with the specified width and height.
• public abstract void setColor(Color c) − This method sets the graphics current color
to the specified color.
• public abstract void setFont(Font font) − This method sets the graphics context's
current font to the specified font.
• public abstract void drawOval(int x, int y, int width, int height) − This method
draws an oval bounded by the specified rectangle from the point (x, y) with the
specified width and height.
• public abstract void fillOval(int x, int y, int width, int height) − This method fills
an oval bounded by the specified rectangle from the point (x, y) with the specified
width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2) − This method draws a
line between points (x1, y1) and (x2, y2)

Example program:
import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
MyFrame()
{
setSize(600, 400);
setTitle("My Application");
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public void paint(Graphics g)
{
g.drawLine(20, 60, 80, 100);
g.drawRect(100, 60, 80, 40);
g.fillRect(200, 60, 80, 40);
g.drawRoundRect(300, 60, 80, 40, 20, 20);
g.fillRoundRect(400, 60, 80, 40, 20, 20);
g.drawOval(20, 120, 80, 40);
g.fillOval(120, 120, 80, 40);
g.drawArc(220, 120, 80, 40, 90, -90);
g.fillArc(320, 120, 80, 40, 90, -90);
int[] x = {20, 100, 80, 20};
int[] y = {200, 180, 240, 260};
g.drawPolygon(x, y, 4);
int[] fillx = {120, 200, 180, 120};
int[] filly = {200, 180, 240, 260};
g.fillPolygon(fillx, filly, 4);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Output:

BorderLayout (LayoutManagers)

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
frame or window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

Example of BorderLayout class: Using BorderLayout() constructor

FileName: Border.java

1. import java.awt.*;
2. import javax.swing.*;
3. public class Border
4. {
5. JFrame f;
6. Border()
7. {
8. f = new JFrame();
9. // creating buttons
10. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
11. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
12. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
13. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
14. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
15. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
16. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
17. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
18. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
19. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
20. f.setSize(300, 300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new Border();
25. }
26. }

Output:

Java GridLayout

The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.

FileName: MyGridLayout.java

1. import java.awt.*;
2. import javax.swing.*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. // adding buttons to the frame
17. f.add(b1); f.add(b2); f.add(b3);
18. f.add(b4); f.add(b5); f.add(b6);
19. f.add(b7); f.add(b8); f.add(b9);
20. // setting grid layout of 3 rows and 3 columns
21. f.setLayout(new GridLayout(3,3));
22. f.setSize(300,300);
23. f.setVisible(true);
24. }
25. public static void main(String[] args) {
26. new MyGridLayout();
27. }
28. }

Output:
Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class

• FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment and a default
5 unit horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.

1. import java.awt.*;
2. import javax.swing.*;
3. public class MyFlowLayout{
4. JFrame f;
5. MyFlowLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. // adding buttons to the frame
13. f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
14. // setting flow layout of right alignment
15. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
16. f.setSize(300,300);
17. f.setVisible(true);
18. }
19. public static void main(String[] args) {
20. new MyFlowLayout();
21. }
22. }

Output:

Java CardLayout

The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.

Constructors of CardLayout Class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly Used Methods of CardLayout Class

o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.
CardLayoutExample

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class CardLayoutExample2 extends JFrame implements ActionListener{
5. CardLayout card;
6. JButton b1,b2,b3;
7. Container c;
8. CardLayoutExample2(){
9. c=getContentPane();
10. card=new CardLayout(40,30);
11. //create CardLayout object with 40 hor space and 30 ver space
12. c.setLayout(card);
13. b1=new JButton("Apple");
14. b2=new JButton("Boy");
15. b3=new JButton("Cat");
16. b1.addActionListener(this);
17. b2.addActionListener(this);
18. b3.addActionListener(this);
19. c.add("a",b1);c.add("b",b2);c.add("c",b3);
20. }
21. public void actionPerformed(ActionEvent e) {
22. card.next(c);
23. }
24. public static void main(String[] args) {
25. CardLayoutExample2 cl=new CardLayoutExample2();
26. cl.setSize(400,400);
27. cl.setVisible(true);
28. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
29. }
30. }

Output:
GridBagLayout

The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.

The components may not be of the same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as its
display area. Each component associates an instance of GridBagConstraints. With the help of
the constraints object, we arrange the component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine the component's size. GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes and can occupy multiple rows or columns.

Constructor

GridBagLayout(): The parameterless constructor is used to create a grid bag layout


manager.

Example Program:

1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41. }
42. }

Output:

You might also like