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

Unit 5 Awt - Swing

Java

Uploaded by

Aryan Gireesh
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)
32 views

Unit 5 Awt - Swing

Java

Uploaded by

Aryan Gireesh
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/ 22

Abstract Window Toolkit (AWT)

AWT contains large number of classes and methods that allows you
to create and manage graphical user interface ( GUI ) applications,
such as windows, buttons, scroll bars,etc. The AWT was designed to
provide a common set of tools for GUI design that could work on a
variety of platforms.

AWT is the foundation upon which Swing is made i.e Swing is a set
of GUI interfaces that extends the AWT. But now a days AWT is
merely used because most GUI Java programs are implemented using
Swing because of its rich implementation of GUI controls and light-
weighted nature.

Component class

Component class is at the top of AWT hierarchy. Component is an


abstract class that encapsulates all the attributes of visual component.
A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.

Container

Container is a component in AWT that contains another component


like button, text field, tables etc. Container is a subclass of
component class. Container class keeps track of components that are
added to another component.

Panel
Panel class is a concrete subclass of Container. Panel does not
contain title bar, menu bar or border. It is container that is used for
holding components.

Window class

Window class creates a top level window. Window does not have
borders and menubar.

Frame

Frame is a subclass of Window and have resizing canvas. It is a


container that contain several different components like button, title
bar, textfield, label etc. In Java, most of the AWT applications are
created using Frame window. Frame class has two different
constructors,
Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Swing

Swing Framework contains a set of classes that provides more


powerful and flexible GUI components than those of AWT. Swing
provides the look and feel of modern Java GUI. Swing library is an
official Java GUI tool kit released by Sun Microsystems. It is used to
create graphical user interface with Java.

Swing classes are defined in javax.swing package and its sub-


packages.
Main Features of Swing Toolkit

1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel

AWT and Swing Hierarchy

Introduction to Swing Classes


JPanel : JPanel is Swing's version of AWT class Panel and uses the
same default layout, FlowLayout. JPanel is descended directly from
JComponent.

JFrame : JFrame is Swing's version of Frame and is descended


directly from Frame class. The component which is added to the
Frame, is refered as its Content.

JWindow : This is Swing's version of Window and has descended


directly from Window class. Like Window it uses BorderLayout by
default.

JLabel : JLabel has descended from JComponent, and is used to


create text labels.

JButton : JButton class provides the functioning of push button.


JButton allows an icon, string or both associated with a button.

JTextField : JTextFields allow editing of a single line of text.

No. Java AWT Java Swing


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

The methods of Component class are widely used in java swing that
are given below.

Method Description

add a component on another


public void add(Component c)
component.

public void setSize(int width,int


sets size of the component.
height)

public void sets the layout manager for the


setLayout(LayoutManager m) component.

sets the visibility of the


public void setVisible(boolean b)
component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

 By creating the object of Frame class (association)


 By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any
other method.

Working with Frame Windows


Here are two of Frame’s constructors:

Frame( )
Frame(String title)
THE JAVA LIBRARY
Setting the Window’s Dimensions

The setSize( ) method is used to set the dimensions of the


window.
Its signature is shown here:

void setSize(int newWidth, int newHeight)

void setSize(Dimension newSize)

The getSize( ) method is used to obtain the current size of a


window.
Its signature is shown here:

Dimension getSize( )
This method returns the current size of the window contained
within the width and height fields of a Dimension object.

Hiding and Showing a Window

void setVisible(boolean visibleFlag)

You can change the title in a frame window using setTitle( ),


which has this general form:

void setTitle(String newTitle)


To intercept a window-close event, you must implement the
windowClosing( ) method of the WindowListener
interface.
Inside windowClosing( ), you must remove the window from
the screen.The example in the next section illustrates this
technique.

LayoutManagers

The LayoutManagers are used to arrange components in a particular


manner. LayoutManager is an interface that is implemented by all the
classes of layout managers. There are following classes that
represents the layout managers:

FlowLayout

The FlowLayout is used to arrange the components in a line, one after


another (in a flow). It is the default layout of 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

1. FlowLayout(): creates a flow layout with centered alignment


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

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

 BorderLayout(): creates a border layout but with no gaps


between the components.

 JBorderLayout(int hgap, int vgap): creates a border layout
with the given horizontal and vertical gaps between the
components.

GridLayout

The GridLayout is used to arrange the components in 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 alongwith given
horizontal and vertical gaps.
CardLayout

The 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

 public void next(Container parent): is used to flip to the next


card of the given container.
 public void previous(Container parent): is used to flip to the
previous card of the given container.
 public void first(Container parent): is used to flip to the first
card of the given container.
 public void last(Container parent): is used to flip to the last
card of the given container.
 public void show(Container parent, String name): is used to
flip to the specified card with the given name.
The Delegation Event Model
The modern approach to handling events is based on the delegation
event model, which defines standard and consistent mechanisms to
generate and process events.
Its concept is quite simple: a source generates an event and sends
it to one or more listeners. In this scheme, the listener simply waits until
it receives an event. Once received, the listener processes the event
and then returns.

Events
Event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the
elements in a graphical user interface.

Event Sources
A source is an object that generates an event.

Each type of event has its registration method.


Here is the general form:
public void addTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event
listener.

For example,
the method that registers a keyboard event listener is called
addKeyListener( ).

The method that registers a mouse motion listener is called


addMouseMotionListener( ).

A source must also provide a method that allows a listener to unregister


an interest in a specific type of event.

The general form of such a method is this:


public void removeTypeListener(TypeListener el)

For example,
to remove a keyboard listener, you would call removeKeyListener( ).
Event Listeners
A listener is an object that is notified when an event occurs. It has two
major requirements.
First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.

Event Classes:

At the root of the Java event class hierarchy is EventObject. It is the


superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ).

The getSource( ) method returns the source of the event.

Its general form is shown here:


Object getSource( )

toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a


subclass of EventObject. It is the superclass (either directly or indirectly)
of all AWT-based events used by the delegation event model.

Its getID( ) method can be used to determine the


type of the event. The signature of this method is shown here:

int getID( )

Event Class Description

ActionEvent: Generated when a button is pressed, a list item is


double-clicked, or a menu item is selected.

AdjustmentEvent :Generated when a scroll bar is manipulated.

ComponentEvent: Generated when a component is hidden, moved,


resized,or becomes visible.
ContainerEvent: Generated when a component is added to or removed
from a container.

FocusEvent: Generated when a component gains or loses


keyboard focus.

ItemEvent: Generated when a check box or list item is clicked; also


occurs when a choice selection is made or a checkable
menu item is selected or deselected.

KeyEvent :Generated when input is received from the keyboard.


MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released; also generated when the mouse enters
or exits a component.

MouseWheelEvent :Generated when the mouse wheel is moved.

TextEvent: Generated when the value of a text area or text field is


changed.

WindowEvent: Generated when a window is activated, closed,


deactivated,deiconified, iconified, opened, or quit.

Event Classes Listener Interfaces


ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Event Listener Interfaces
Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package.

The following specific methods that are contained in each interface.

ActionListener Interface

void actionPerformed(ActionEvent ae)

AdjustmentListener Interface

void adjustmentValueChanged(AdjustmentEvent ae)

ComponentListener Interface
This interface defines four methods that are invoked when a component
is resized,
moved, shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

ContainerListener Interface

void componentAdded(ContainerEvent ce)


void componentRemoved(ContainerEvent ce)

The FocusListener Interface

void focusGained(FocusEvent fe)


void focusLost(FocusEvent fe)

The ItemListener Interface

void itemStateChanged(ItemEvent ie)


The KeyListener Interface

The general forms of these methods are shown here:

void keyPressed(KeyEvent ke)


void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

The MouseListener Interface

The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)


void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

The MouseMotionListener Interface

void mouseDragged(MouseEvent me)


void mouseMoved(MouseEvent me)

The MouseWheelListener Interface

void mouseWheelMoved(MouseWheelEvent mwe)

The TextListener Interface

void textChanged(TextEvent te)

The WindowFocusListener Interface


void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)

WindowListener:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
JButton

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

Constructor Description
JButton() It creates a button with no text and icon.
JButton(String
It creates a button with the specified text.
s)
It creates a button with the specified icon
JButton(Icon i)
object.

Commonly used Methods of AbstractButton class:

Methods Description
It is used to set specified text
void setText(String s)
on button
It is used to return the text of
String getText()
the button.
It is used to enable or disable
void setEnabled(boolean b)
the button.
It is used to set the specified
void setIcon(Icon b)
Icon on the button.
It is used to get the Icon of the
Icon getIcon()
button.
It is used to set the mnemonic
void setMnemonic(int a)
on the button.
void It is used to add the action
addActionListener(ActionListener a) listener to this object.
JTextField:

object of a JTextField class is a text component that allows the


editing of a single line text. It inherits JTextComponent class.

Commonly used Constructors:

Constructor Description
JTextField() Creates a new TextField
Creates a new TextField initialized with the
JTextField(String text)
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
Creates a new empty TextField with the
JTextField(int columns)
specified number of columns.

JTextArea

The object of a JTextArea class is a multi line region that displays


text. It allows the editing of multiple line text. It inherits
JTextComponent class

Commonly used Constructors:

Constructor Description
Creates a text area that displays no text
JTextArea()
initially.
Creates a text area that displays specified text
JTextArea(String s)
initially.
Creates a text area with the specified number
JTextArea(int row, int
of rows and columns that displays no text
column)
initially.
JTextArea(String s, int Creates a text area with the specified number
row, int column) of rows and columns that displays specified
text.
Commonly used Methods:

Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.

Java JPasswordField

The object of a JPasswordField class is a text component specialized


for password entry. It allows the editing of a single line of text. It
inherits JTextField class.

Commonly used Constructors:

Constructor Description
Constructs a new JPasswordField, with a
JPasswordField() default document, null starting text string,
and 0 column width.
JPasswordField(int Constructs a new empty JPasswordField
columns) with the specified number of columns.
Constructs a new JPasswordField initialized
JPasswordField(String text)
with the specified text.
JPasswordField(String text, Construct a new JPasswordField initialized
int columns) with the specified text and columns.
Java JComboBox

The object of Choice class is used to show popup menu of choices.


Choice selected by user is shown on the top of a menu. It inherits
JComponent class.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

1.

public class JComboBox extends JComponent implements ItemS


electable, ListDataListener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

Creates a JComboBox with a default data


JComboBox()
model.

JComboBox(Object[] Creates a JComboBox that contains the


items) elements in the specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the


items) elements in the specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the


item list.
It is used to delete an item to
void removeItem(Object anObject)
the item list.

It is used to remove all the


void removeAllItems()
items from the list.

It is used to determine whether


void setEditable(boolean b)
the JComboBox is editable.

void It is used to add the


addActionListener(ActionListener a) ActionListener.

void addItemListener(ItemListener It is used to add the


i) ItemListener.

You might also like