[Go to site: main page, start]

0% found this document useful (0 votes)
5 views29 pages

Introduction To Java Programming

The document explains the concepts of abstract classes and interfaces in Java, highlighting their definitions, differences, and examples. It also covers Java inner classes, event handling, and the delegation event model, detailing event sources, listeners, and various event classes. Additionally, it introduces the Abstract Window Toolkit (AWT) for GUI development in Java, along with its components and classes.

Uploaded by

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

Introduction To Java Programming

The document explains the concepts of abstract classes and interfaces in Java, highlighting their definitions, differences, and examples. It also covers Java inner classes, event handling, and the delegation event model, detailing event sources, listeners, and various event classes. Additionally, it introduces the Abstract Window Toolkit (AWT) for GUI development in Java, along with its components and classes.

Uploaded by

jananippriya18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract classA{}

abstractmethod
1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


abstract class Bike{
abstract void run();
}
classHonda4 extends Bike{ voidrun()
{[Link]("running safely..");} public
static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
1. }
runningsafely..
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

There are mainly three reasons to use interface. They are given below.
o It is used to achieveabstraction.
o By interface, we can support the functionality of multipleinheritance.
o It can be used to achieve loosecoupling.

JAVA PROGRAMMING Page 1


Abstract class Interface
1) Abstract class can have Interface can have only abstract methods. Since
abstract and non- Java 8, it can have default and static
abstractmethods. methodsalso.
2) Abstract class doesn't support Interface supports multiple inheritance.
multipleinheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation ofinterface. abstract class.
5) The abstract keyword is used to Theinterface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java Inner Classes
Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.

Syntax of Inner class


1. classJava_Outer_class{
2. //code
3. classJava_Inner_class{
4. //code
5. }

JAVA PROGRAMMING Page 2


Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because
it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested [Link] non-static nested
classes are also known as inner classes.

o Non-static nested class (innerclass)


1. Member inner class
2. Anonymous innerclass
3. Local inner class
o Static nestedclass

EVENT HANDLING
Event handling is at the core of successful applet programming. Most events to which the applet
will respond are generated by the user. The most commonly handled events are those generated by
the mouse, the keyboard, and various controls, such as a push button.
Events are supported by the [Link] package.

The Delegation Event Model


The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events.

Its concept is quite simple: a source generates an event and sends it to one or more
listeners. In this scheme, the listener simply waits until it receives an event. Once received, the
listener processes the event and then returns.

The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events. 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.

JAVA PROGRAMMING Page 3


EVENTS
In the delegation model, an 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. Some of the activities that cause events to be generated are pressing a button, entering
a character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value,
software or hardware failure occurs, or an operation is completed.
EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method.
Here is the general form:
public void add Type Listener( Type Listener el )
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.
The methods that receive and process events are defined in a set of interfaces found in
[Link].

For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root
of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass for all
events.
It’s one constructor is shown here:
EventObject(Object src )
EventObject contains two methods:
getSource( ) and toString( ) .
The getSource( ) method returns the source of the event. Ex: Object getSource( )
toString( ) returns the string equivalent of the event.
The package [Link] defines several types of events that are generated by various user
interface elements.
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.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so 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. (Added by Java 2, version 1.4)
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.

The ActionEvent Class


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected. The ActionEvent class defines four integer constants that can be used to
identify any modifiers associated with an action event: ALT_MASK , CTRL_MASK ,
META_MASK , and SHIFT_MASK .
ActionEvent has these three constructors:
ActionEvent(Object src , int type , String cmd )
ActionEvent(Object src , int type , String cmd , int modifiers )
ActionEvent(Object src , int type, String cmd, long when , int modifiers )

The ComponentEvent Class


// ComponentEvent is generated when the size, position, or visibility of a component is
changed. There are four types of component events. The constants and their meanings are
shown here:
COMPONENT_HIDDEN The component was hidden.
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.
The ContainerEvent Class
//ContainerEvent is generated when a component is added to or removed from a container.
There are two types of container events.

COMPONENT_ADDED and
COMPONENT_REMOVED The KeyEvent Class
//KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED .
The first two events are generated when any key is pressed or released. The last event occurs
only when a character is generated.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a
component. MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2,
v1.4).
The WindowEvent Class
There are ten types of window events. The WindowEvent class defines integer constants that
can be used to identify them. The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input
focus. WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input
focus. WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
EVENT LISTENER INTERFACES
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed,
released, or typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
The delegation event model has two parts: sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the [Link] package.
The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event
occurs.
Its general form is shown here: void actionPerformed(ActionEvent ae )
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes.
Its general form is shown here: void itemStateChanged(ItemEvent ie )
The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked
when a character has been entered. For example, if a user presses and releases the key, three
events are generated in A sequence: key pressed, typed, and released.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke )
void keyReleased(KeyEvent ke )
void keyTyped(KeyEvent ke )
The MouseListener Interface

This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method
is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( )
methods are invoked when the mouse is pressed and released, respectively.
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


This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.

Their general forms are shown here:


void mouseDragged(MouseEvent me )
void mouseMoved(MouseEvent me )
The TextListener Interface
This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field.
Its general form is shown here: void textChanged(TextEvent te )

Handling Mouse Events


To handle mouse events, we must implement the MouseListener and the MouseMotion Listener
interfaces.
Handling Keyboard Events
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the
keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated
and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked.
Thus, each time the user presses a key, at least two and often three events are generated. If all
you care about are actual characters, then you can ignore the information passed by the key press
and release events.
Adapter Classes
Java provides a special feature, called an adapter class , that can simplify the creation of
event handlers in certain situations. An adapter class provides an empty implementation of all
methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the event that
are handled by a particular event listener interface.
For example
The MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ) .
The signatures of these empty methods are exactly as defined in the MouseMotionListener
interface. If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and implement mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you.
Adapter Class : ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter
MouseMotionAdapter WindowAdapter.
Listener Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener
MouseMotionListener WindowListener.

ABSTRACT WINDOW TOOLKIT (AWT)


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based application
in java. Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components uses the resources of
system. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous
classes and methods that allow you to create and manage windows.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java's largest packages.
Class Description
AWTEvent Encapsulates AWT events.
AWTEventMulticaster Dispatches events to multiple
listeners. BorderLayout Border layouts use five components:
North, South, East, West, and Center.
CardLayout Card layouts emulate index
cards. Only the one on top is
showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box
controls. CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
Color Manages colors in a portable, platform-independent fashion.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
Dimension Specifies the dimensions of an object. The width is stored in
width , and the height is stored in height .
Event Encapsulates events.
FlowLayout The flow layout manager. Flow layout positions components left
to right, top to bottom.
Frame Creates a standard window that has a title bar, resize corners,
and a menu bar.
Graphics Encapsulates the graphics context.
Control Fundamentals
The AWT supports the following types of controls:
3. Labels
4. Push buttons
5. Check boxes
6. Choice lists
7. Lists
8. Scroll bars
9. Text editing

User interaction with the program is of two types:


CUI (Character User Interface): In CUI user interacts with the application by
typing characters or commands. In CUI user should remember the commands. It is
not user friendly.
2. GUI (Graphical User Interface): In GUI user interacts with the application through graphics.
GUI is user friendly. GUI makes application attractive. It is possible to simulate real object in
GUI programs. In java to write GUI programs we can use awt (Abstract Window Toolkit)
package.

Java AWT Class Hierarchy


The hierarchy of Java AWT classes is given below.

Container
The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog
and Panel.
Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
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.
public void setVisible(boolean status) changes the visibility of the component, by
default false.

Listeners and Listener Methods:


Listeners are available for components. A Listener is an interface that listens to an event from a
component. Listeners are available in [Link] package. The methods in the listener
interface are to be implemented, when using that listener.
AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
Buttons:
The most widely used control is the push button. A push button is a component that contains a
label and that generates an event when it is pressed. Push buttons are objects of type Button.
Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = [Link]();
To set the label of the button: [Link]("label");
To get the label of the button clicked: String str = [Link]();

Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group.
TextField:
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea .

\{ Demonstrate
TextArea. import
[Link].*; import
[Link].*;
/*
<applet code="TextAreaDemo" width=300
height=250> </applet>
*/
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " + "a software design.\n" + "One way is to
make it so simple\n" + "that there are obviously no deficiencies.\n" + "And the other way is to
make it so complicated\n" + "that there are no obvious deficiencies.\n\n" + " -C.A.R. Hoare\n\n"
+ "There's an old story about the person who wished\n" + "his computer were as easy to use as
his telephone.\n" + "That wish has come true,\n" + "since I no longer know how to use my
telephone.\n\n" + " -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons. A Radio button represents a round shaped button such that only one can be
selected from a panel. Radio button can be created using CheckboxGroup class and
Checkbox classes.
To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = [Link] ();
·To know the selected checkbox label: String label = [Link]().getLabel ();

\{ Demonstrate check box group.


import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/

public class CBGroup extends Applet implements ItemListener


{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false); mac = new
Checkbox("MacOS", cbg, false);
add(Win98);
add(winNT);
add(solaris);
add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
\{ Display current state of the check
boxes. public void paint(Graphics g)
{
msg = "Current selection: ";
msg += [Link]().getLabel();
[Link](msg, 6, 100);
}
}
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. Choice menu is a popdown list of items. Only
one item can be selected.
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: [Link] ("text");
· To know the name of the item selected from the choice menu:
String s = [Link] ();
· To know the index of the currently selected item: int i = [Link]();
This method returns -1, if nothing is selected.
//Demonstrate Choice
lists. import
[Link].*; import
[Link].*;
import [Link].*;
/*
<applet code="ChoiceDemo" width=300
height=180> </applet>
*/
public class ChoiceDemo extends Applet implements ItemListener
{ Choice os, browser;
String msg = ""; public
void init() { os = new
Choice(); browser = new
Choice();
//add items to os list
[Link]("Windows 98/XP");
[Link]("Windows NT/2000");
[Link]("Solaris");
[Link]("MacOS");
\{ add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer
4.0"); [Link]("Internet
Explorer 5.0");
[Link]("Internet Explorer
6.0"); [Link]("Lynx 2.4");
[Link]("Netscape 4.x");
\{ add choice lists to
window add(os);
add(browser);
\{ register to receive item
events
[Link](this);
[Link](
this)
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g)
{ msg = "Current OS: ";
msg += [Link]();
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}

Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections. List provides these constructors:
List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
· To create a list
box: List lst = new List();
(or)
List lst = new List (3, true);
This list box initially displays 3 items. The next parameter true represents that the user can
select more than one item from the available items. If it is false, then the user can select
only one item.
= To add items to the list box: [Link]("text");
= To get the selected items: String x[] = [Link]();
= To get the selected indexes: int x[] = [Link] ();
Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. Scrollbar class is useful to create
scrollbars that can be attached to a frame or text area. Scrollbars can be arranged vertically or
horizontally.
\{ To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step, min,
max); alignment: [Link], [Link]
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar length
min: minimum value (e.g. 0)
max: maximum value (e.g. 300)
· To know the location of a scrollbar: int n = [Link] ();
· To update scrollbar position to a new position: [Link] (int position);
· To get the maximum value of the scrollbar: int x = [Link] ();
· To get the minimum value of the scrollbar: int x = [Link] ();
· To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.

SWINGS
Swing is a set of classes that provides more powerful and flexible components than are
possible with the AWT. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java
Foundation Classes (JFC) that is used to create window-based applications. It is built on
the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes.

Unlike AWT components, Swing components are not implemented by platform specific
code. Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.

The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Differences between AWT and Swing

AWT Swing

AWT components are called Heavyweight Swings are called light weight component
component. because swing components sits on the top of
AWT components and do the work.

AWT components are platform dependent. Swing components are made in purely java and
they are platform independent.

AWT components require [Link] package. Swing components require [Link]


package.

AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very
much richer functionality.

AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java Foundation
classes).

This feature is not supported in AWT. We can have different look and feel in Swing.

Using AWT, you have to implement a lot of Swing has them built in.
things yourself.
This feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed pane w

The Swing component classes are:


Class Description
AbstractButton Abstract superclass for Swing buttons.
ButtonGroup Encapsulates a mutually exclusive set of
buttons. ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push button class.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (combination of a drop-down list & text
field). JLabel The Swing version of a label.
JRadioButton The Swing version of a radio button.
JScrollPane Encapsulates a scrollable
window. JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
JTree Encapsulates a tree-based control.
Hierarchy for Swing components:
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not foundin Applet.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
JFrame
Create an object to JFrame: JFrame ob = new JFrame ("title"); (or)
Create a class as subclass to JFrame class: MyFrame extends JFrame
Create an object to that class : MyFrame ob = new MyFrame ();
Example: Write a program to create a frame by creating an object to JFrame
class. //A swing Frame
import [Link].*;
class MyFrame
{
public static void main (String agrs[])
{ JFrame jf = new JFrame ("My Swing
Frame..."); [Link] (400,200);
[Link] (true);
[Link] (JFrame.EXIT_ON_CLOSE);
}
}

Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here: getDefaultCloseOperation (constant);
where the constant can be any one of the following:
◼ JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
◼ JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible
on the screen. The JVM may also terminate.
◼ JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation upon
clicking on close button.
◼ JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.

Window Panes: In swings the components are attached to the window panes only. A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in [Link] which contains a free area
inside it, this free area is called 'window pane'. Four types of window panes are available in
[Link] package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any components to
be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use
getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root
pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several components
as a group, we attach them in the layered pane. We can reach this pane by calling
getLayeredPane () method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached to this
pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame:
paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component
in swing. We should override this method in our class. In the following example, we are writing
our class MyPanel as a subclass to JPanel and override the painComponent () method.
TEXT FIELDS
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows you to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int
cols) JTextField(String s)
BUTTONS
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that
allow you to control the behavior of buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or
both to be associated with the push button. Some of its constructors are shown here:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it. The image is specified by
ImageIcon class object.
CHECK BOXES
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides
support for two-state buttons. Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
RADIO BUTTONS
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-
state buttons. Some of its constructors are shown here:

You might also like