Java Programming Unit 5
Java Programming Unit 5
5.1.1 Introduction
Computer users today expect to interact with their computers using a graphical user interface (GUI). Java can
be used to write GUI programs ranging from simple applets which run on a Web page to sophisticated stand-
alone applications.
GUI programs differ from traditional “straight-through” programs that you have encountered in the first few
chapters of this book. One big difference is that GUI programs are event-driven. That is, user actions such as
clicking on a button or pressing a key on the keyboard generate events, and the program must respond to these
events as they occur.
And of course, objects are everywhere in GUI programming. Events are objects. Colors and fonts are objects.
GUI components such as buttons and menus are objects. Events are handled by instance methods contained in
objects. In Java, GUI programming is object-oriented programming.
There are two basic types of GUI program in Java: stand-alone applications and applets. An applet is a
program that runs in a rectangular area on a Web page. very complex. We will look at applets in the next
section.
A stand-alone application is a program that runs on its own, without depending on a Web browser. You’ve
been writing stand-alone applications all along. Any class that has a main() routine defines a stand-alone
application; running the program just means executing this main() routine.
A GUI program offers a much richer type of user interface, where the user uses a mouse and keyboard to
interact with GUI components such as windows, menus, buttons, check boxes, text input boxes, scroll bars, and
so on. The main routine of a GUI program creates one or more such components and displays them on the
computer screen. Very often, that’s all it does. Once a GUI component has been created, it follows its own
programming—programming that tells it how to draw itself on the screen and how to respond to events such as
being clicked on by the user.
Java Programming 3
A GUI program doesn’t have to be immensely complex. We can, for example, write a very simple GUI “Hello
World” program that says “Hello” to the user, but does it by opening a window where the the greeting is
displayed:
import javax.swing.JOptionPane;
When this program is run, a window appears on the screen that contains the message “Hello World!”. The
window also contains an “OK” button for the user to click after reading the message. When the user clicks this
button, the window closes and the program ends. By the way, this program can be placed in a file named
HelloWorldGUI1.java, compiled, and run just like any other Java program.
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface. One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means that the look and feel
of a component is defined by the platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.The use of native peers led to several problems. First, because
of variations between operating systems, a component might look, or even act, differently on different
platforms. This variability threatened java’s philosophy: write once, run anywhere.Second, the look and feel of
each component was fixed and could not be changed. Third,the use of heavyweight components caused some
frustrating restrictions.
Java Programming 4
Model :
This is the data layer which consists of the business logic of the system.
It consists of all the data of the application
It also represents the state of the application.
It consists of classes which have the connection to the database.
The controller connects with model and fetches the data and sends to the view layer.
The model connects with the database as well and stores the data into a database which is connected to
it.
View :
Controller:
3. The server looks for or search for the appropriate resource in the resource pool.
4. If the resource is not available server side program displays a user friendly message (page cannot be
displayed). If the resource is available, that program will execute gives its result to server, server interns gives
response to that client who makes a request.
5. When server want to deals with database to retrieve the data, server side program sends a request to the
appropriate database.
6. Database server receives the server request and executes that request.
7. The database server sends the result back to server side program for further processing.
8. The server side program is always gives response to ‘n’ number of clients concurrently.
Java Programming 6
MVC in Swing
Swing actually uses a simplified variant of the MVC design called the model-delegate . This design combines
the view and the controller object into a single element, the UI delegate , which draws the component to the
screen and handles GUI events. Bundling graphics capabilities and event handling is somewhat easy in Java,
since much of the event handling is taken care of in AWT. As you might expect, the communication between
the model and the UI delegate then becomes a two-way street, as shown in Figure below.
So let’s review: each Swing component contains a model and a UI delegate. The model is responsible for
maintaining information about the component’s state. The UI delegate is responsible for maintaining
information about how to draw the component on the screen. In addition, the UI delegate (in conjunction with
AWT) reacts to various events that propagate through the component.
Note that the separation of the model and the UI delegate in the MVC design is extremely advantageous. One
unique aspect of the MVC architecture is the ability to tie multiple views to a single model. For example, if
you want to display the same data in a pie chart and in a table, you can base the views of two components on a
single data model. That way, if the data needs to be changed, you can do so in only one place—the views
update themselves accordingly
Java Programming 7
5.1.4 Components
Component is an object having a graphical representation that can be displayed on the screen and that can
interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface.
A Component is an abstract super class for GUI controls and it represents an object with graphical
representation.
Component Description
Label 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 theuser. Label defines the following constructors
Check Box A check box is a graphical component that can be in either an on (true) or off (false)
state.
Check Box Group The CheckboxGroup class is used to group the set of checkbox.
List The List component presents the user with a scrolling list of text items.
Text Field A TextField object is a text component that allows for the editing of a single line of text.
Text Area A TextArea object is a text component that allows for the editing of a multiple lines of
text.
Choice A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
Canvas A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
Image An Image control is superclass for all image classes representing graphical images.
Scroll Bar A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Dialog A Dialog control represents a top-level window with a title and a border used to take
Java Programming 9
File Dialog A FileDialog control represents a dialog window from which the user can select a file.
Method Description
public void setSize(intwidth,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.
void remove(Component obj) Here, obj is a reference to the control you want to
remove.
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.
The second version creates a label that contains thestring specified by str. This string is left-justified.
The third version creates a label that contains the string specified by str using the alignment specified by how.
The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
You can set or change the text in a label by using the setText( ) method. You can obtain the current label by
calling getText( ).
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.
Buttons
Perhaps 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.
After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling
getLabel( ).
String getLabel( )
1.
Java Programming 12
Check Box
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. Check boxes are objects of the Checkbox class.
The first form creates a check box whose label is initially blank. The state of the check box isunchecked.
The second form creates a check box whose label is specified by str. The state ofthe check box is unchecked.
The third form allows you to set the initial state of the checkbox. If on is true, the check box is initially checked;
otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by
cbGroup. If this check box is not part of a group, then cbGroup must be null. (Check box groups are described
in the next section.) The value of on determines the initial state of thecheck box.
To retrieve the current state of a check box, call getState( ). To set its state, callsetState( ). You can obtain the
current label associated with a check box by callinggetLabel( ). To set the label, call setLabel( ).
boolean getState( )
String getLabel( )
Java Programming 13
void setLabel(String str)Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed
in str becomes the new label associated with the invoking check box.
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. To create a set of
mutually exclusive check boxes, you must firstdefine the group to which they will belong and then specify that
group when you constructthe check boxes.
You can determine which check box in a group is currently selected by calling getSelectedCheckbox( ). You
can set a check box by calling setSelectedCheckbox( ).
Checkbox getSelectedCheckbox( )
Here, which is the check box that you want to be selected. The previously selected check box will be turned off.
Java Programming 14
What are the differences between JToggle buttion and Radio buttion? [2marks]
Toggle Button:
Toggles should be used to represent an action, like turning something on or off, or starting or stopping an
activity. It should be clear which state is on and which state is off. As the name suggest a button whose state can
be toggled from on to off or vice-versa. For example a Switch in your home to turn a particular light on or off.
Radio Button:
Java Programming 15
Radio buttons should be used when the user can select one, and only one, option from a list of items. The button
should be circular and become filled in when it is selected. Its name comes from the concept of buttons in Radio
where for first station you press first button and for second station you press second button and so forth. So you
can choose from multiple options. But at a time only one will be selected.
Choice
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. When inactive, a Choice component takes up only enough space to show the currently
selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made.
Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object.
Choice only defines the default constructor, which creates an empty list.
To add a selection to the list, call add( ). It has this general form:
Here, name is the name of the item being added. Items are added to the list in the order inwhich calls to add( )
occur.
To determine which item is currently selected, you may call either getSelectedItem( )or getSelectedIndex( ).
These methods are shown here:
String getSelectedItem( );
Java Programming 16
int getSelectedIndex( );
The getSelectedItem( ) method returns a string containing the name of the item.getSelectedIndex( ) returns the
index of the item. The first item is at index 0. By default,the first item added to the list is selected.
To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item using the
select( ) method with either a zero-based integer index or a string that will match a name in the list. Given an
index you can obtain the name associated with the item at that index by calling getItem( ),
int getItemCount( );
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike theChoice 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 toallow multiple selections.
List constructors:
The first version creates a List control that allows only one item to be selected at any onetime.
In the second form, the value of numRows specifies the number of entries in the list that will always be visible
(others can be scrolled into view as needed).
In the third form, if multipleSelect is true, then the user may select two or more items at a time. If it is false,
then only one item may be selected.
To add a selection to the list, call add( ). It has the following two forms:
Here, name is the name of the item added to the list. The first form adds items to the end of the list. The second
form adds the item at the index specified by index. Indexing begins at zero. You can specify –1 to add the item
to the end of the list.
For lists that allow only single selection, you can determine which item is currently selected by calling either
getSelectedItem( ) or getSelectedIndex( ).
Java Programming 18
String getSelectedItem( )
int getSelectedIndex( )
For lists that allow multiple selection, you must use either getSelectedItems( ) or getSelectedIndexes( ), shown
here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected items.
getSelectedIndexes( ) returns an array containing the indexes of the currently selected items.
To obtain the number of items in the list, call getItemCount( ). You can set the currently
selected item by using the select( ) method with a zero-based integer index. Given an index, you can obtain the
name associated with the item at that index bycalling getItem( )
These methods
int getItemCount( );
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.
TextField is a subclass of TextComponent.
TextField constructors:
The second form creates a text field that is numChars characters wide.
The third form initializes the text field with the string contained in str.
The fourth form initializes a text field and sets its width.
TextField provides several methods that allow you to utilize a text field.
Java Programming 20
String getText( )------ To obtain the string currently contained in the text field,
void setText(String str)------ To set the text Here, str is the new string.
String getSelectedText( )------ program can obtain the currently selected text
void select(int startIndex, int endIndex)------ The user can select a portion of the text in a text field. Also, you
can select a portion of text under program control. The select( ) method selects the charactersbeginning at
startIndex and ending at endIndex–1.
boolean isEditable( )------ returns true if the text may be changed and false if not
void setEditable(boolean canEdit)------= if canEdit is true, the text may be changed. If it is false, the text cannot
be altered.
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.
Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width,
in characters. Initial text can be specified by str. In the fifth form, you can specify the scroll bars that you want
the control to have. sBars must be one of these values: SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_VERTICAL_ONLY
void append(String str);------ appends the string specified by str to the end of the current text
void insert(String str, int index);------ inserts the string passed in str at the specified index
void replaceRange(String str, int startIndex, int endIndex);------ It replaces the characters from startIndex to
endIndex–1, with the replacement text passed in str
Java Programming 22
.5.1.5 Container
Abstract Windowing Toolkit (AWT): Abstract Windowing Toolkit (AWT) is used for GUI programming in
java.
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.
Window:
The window is the container that have no borders and menubars. 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 MenuBars. It can have other components like
button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have MenuBars. It can have other components like
button, textfield etc.
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);/*setting button position public void setBounds(int xaxis, int yaxis, int width, int
height); have been used in the above example that sets the position of the button.*/
add(b);//adding button into frame
Java Programming 24
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Java Programming 25
A container has a so‐called layout manager to arrange its components. The layout managers provide a level of
abstraction to map your user interface on all windowing systems, so that the layout can be
platform‐independent.
Flow Layout
Border Layout
Grid Layout
Card Layout
// java.awt.Container
To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to:
1. Construct an instance of the chosen layout object, via new and constructor, e.g., new FlowLayout())
2. Invoke the setLayout() method of the Container, with the layout object created as the argument;
3. Place the GUI components into the Container using the add() method in the correct order; or into the
correct zones.
For example,
// Allocate a new Layout object. The Panel container sets to this layout.
pnl.setLayout(new FlowLayout());
pnl.add(new JLabel("One"));
Java Programming 26
pnl.add(new JLabel("Two"));
pnl.add(new JLabel("Three"));
......
You can get the current layout via Container's getLayout() method.
System.out.println(pnl.getLayout());
// java.awt.FlowLayout[hgap=5,vgap=5,align=center]
Panel (and Swing's JPanel) provides a constructor to set its initial layout manager. It is because a primary
function of Panel is to layout a group of component in a particular layout.
FlowLayout:
In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the order that
they are added (via method aContainer.add(aComponent)). When one row is filled, a new row will be started.
The actual appearance depends on the width of the display window.
Constructors
public FlowLayout();
Note: alignment :
Default value:
Example
import java.awt.*;
import java.awt.event.*;
public AWTFlowLayoutDemo ()
setLayout(new FlowLayout());
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
}
Java Programming 29
GridLayout
In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns inside the Container.
Components are added in a left-to-right, top-to-bottom manner in the order they are added (via
method aContainer.add(aComponent)).
Constructors
Example
import java.awt.*;
import java.awt.event.*;
public AWTGridLayoutDemo () {
// "super" Frame sets layout to 3x2 GridLayout, horizontal and vertical gaps of 3 pixels
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
}
Java Programming 31
BorderLayout
In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH,
and CENTER. Components are added using method aContainer.add(aComponent, zone), where zone is
either BorderLayout.NORTH (or PAGE_START), BorderLayout.SOUTH (or PAGE_END), BorderLayout.WE
ST (or LINE_START), BorderLayout.EAST (or LINE_END), or BorderLayout.CENTER.
You need not place components to all the 5 zones. The NORTH and SOUTH components may be stretched
horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may
stretch both horizontally and vertically to fill any space left over.
Constructors
public BorderLayout();
Example
import java.awt.*;
import java.awt.event.*;
public AWTBorderLayoutDemo ( )
// "super" Frame sets layout to BorderLayout, horizontal and vertical gaps of 3 pixels
add(btnNorth, BorderLayout.NORTH);
Java Programming 32
add(btnSouth, BorderLayout.SOUTH);
add(btnCenter, BorderLayout.CENTER);
add(btnEast, BorderLayout.EAST);
add(btnWest, BorderLayout.WEST);
}
Java Programming 33
Question: differentiate between grid layout and border layout managers.[2 marks]
BorderLayout - Lays out components in BorderLayout.NORTH, EAST, SOUTH, WEST, and CENTER
sections.
bord = new BorderLayout(); Creates BorderLayout. Widgets
added with constraint to tell where.
bord = new BorderLayout(h, v); Creates BorderLayout with horizonal
and vertical gaps sizes in pixels.
p.add(widget, pos); Adds widget to one of the 5 border
layout regions, pos (see list above).
GridLayout - Lays out components in equal sized rectangular grid, added r-t-l, top-to-bottom.
grid = new GridLayout(r, c); Creates GridLayout with specified
rows and columns.
grid = new GridLayout(r,c,h,v); As above but also specifies
horizontal and vertical space
between cells.
p.add(widget); Adds widget to the next left-to-right,
top-to-bottom cell.
GridLayout
A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each
component is placed inside a rectangle
When a component is added, it is placed in the next position in the grid, which is filled row by row, from the first
to last column
BorderLayout
Arranges components into five areas: North, South, East, West, and Center
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center.
Each region is can contain only one component and each component in each region is identified by the
corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.
We can add a single component at each of the four compass directions (specified by the Strings "North", "South",
"East", or "West", as well as at the "Center". Of course, the component we add can be a container, which contains
multiple components (managed by another layout manager).
Java Programming 34
Java 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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
Java Programming 35
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.The
components may not be of 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 constraints object we arrange component's display area on the
grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.
Useful Methods
Modifier and Method Description
Type
void addLayoutComponent(String It has no effect, since this layout manager does not
name, Component comp) use a per-component string.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public GridBagLayoutExample() {
setLayout(grid);
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Java Programming 38
Java adopts the so-called "Event-Driven" (or "Event-Delegation") programming model for event-handling, similar to most of
the visual programming languages, such as Visual Basic.
In event-driven programming, a piece of event-handling codes is executed (or called back by the graphics subsystem) when an
event was fired in response to an user input (such as clicking a mouse button or hitting the ENTER key in a text field).
Call Back methods
In the above examples, the method actionPerformed() is known as a call back method. In other words, you never
invoke actionPerformed() in your codes explicitly. The actionPerformed() is called back by the graphics subsystem under certain
circumstances in response to certain user actions.
Source, Event and Listener Objects
The AWT's event-handling classes are kept in package java.awt.event.
Three kinds of objects are involved in the event-handling: a source, listener(s) and an event object.
The source object (such as Button and Textfield) interacts with the user. Upon triggered, the source object creates
an event object to capture the action (e.g., mouse-click x and y, texts entered, etc). This event object will be messaged to all
the registered listener object(s), and an appropriate event-handler method of the listener(s) is called-back to provide the
Java Programming 39
response. In other words, triggering a source fires an event to all its listener(s), and invoke an appropriate event handler of the
listener(s).
To express interest for a certain source's event, the listener(s) must be registered with the source. In other words, the listener(s)
"subscribes" to a source's event, and the source "publishes" the event to all its subscribers upon activation. This is known
as subscribe-publish or observable-observer design pattern.
1. The source object registers its listener(s) for a certain type of event.
(A source fires an event when triggered. For example, clicking a Button fires an ActionEvent,
clicking a mouse button fires MouseEvent, typing a key fires KeyEvent, and etc.)
3. The source create a XxxEvent object, which encapsulates the necessary information about the activation.
For example, the (x, y) position of the mouse pointer, the text entered, etc.
4. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the appropriate handler
on the listener(s), which provides the programmed response
5.2.2 Events
Changing the state of an object is known as an Event. For example, click on button, dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event handling.
It canbe 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. Many other user operations could also be cited as
examples.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,a software or hardware
failure occurs, or an operation is completed. You are free to define events that are appropriate for your
application.
Asource 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. Asource 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:
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 methodthat registers a mouse motion
listener is called addMouseMotionListener( ). When an eventoccurs, all registered listeners are notified and
receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent
only to listeners that register to receive them.
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:
Here, Type is the name of the event, and el is a reference to the event listener. For example,to remove a
keyboard listener, you would call removeKeyListener( ).The methods that add or remove listeners are provided
by the source that generates events. For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.
First, it must have been registered with one or more sources to receive notifications about
specific types of events.
The methods that receive and process events are defined in a set of interfaces found in java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse
is dragged or moved. Any object may receive and process one or both of these events if it provides an
implementation of this interface.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all
events. Its one constructor is shown here:
EventObject(Object src);
For registering the component with the Listener, many classes provide the registration methods.
For example:
• Button
• MenuItem
• TextField
• TextArea
• Checkbox
• Choice
• List
Mouse Event:
A MouseEvent is fired when you press, release, or click (press followed by release) a mouse-button (left
or right button) at the source object; or position the mouse-pointer at (enter) and away (exit) from the
source object.
The Java MouseListener is notified whenever you change the state of mouse
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.
1. public abstract void mouseClicked(MouseEvent e); // Called-back when the mouse-button has been
clicked on the source.
2. public abstract void mouseEntered(MouseEvent e); //Called-back when the mouse-pointer has
entered the source
3. public abstract void mouseExited(MouseEvent e); //Called-back when the mouse-pointer has exited
the source
Java Programming 44
4. public abstract void mousePressed(MouseEvent e); // Called-back when a mouse-button has been
pressed on the source
5. public abstract void mouseReleased(MouseEvent e); //Called-back when a mouse-button has been
released on the source
import java.awt.*;
import java.awt.event.*;
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
l.setText("Mouse Clicked");
l.setText("Mouse Entered");
l.setText("Mouse Exited");
l.setText("Mouse Pressed");
l.setText("Mouse Released");
new MouseListenerExample();
Output:
Java Programming 46
import java.awt.*;
import java.awt.event.*;
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
Graphics g=getGraphics();
g.setColor(Color.Green);
g.fillOval(e.getX(),e.getY(),20,20);
new MouseMotionListenerExample();
Output:
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
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
new KeyAdapterExample();
}
}
Output:
......
private class MyNestedClass1 { ...... } // an nested class defined inside the outer class
public static class MyNestedClass2 { ...... } // an "static" nested class defined inside the outer class
......
1. A nested class is a proper class. That is, it could contain constructors, member variables and member
methods. You can create an instance of a nested class via the new operator and constructor.
2. A nested class is a member of the outer class, just like any member variables and methods defined inside
a class.
3. Most importantly, a nested class can access the private members (variables/methods) of the enclosing
outer class, as it is at the same level as these private members. This is the property that makes inner class useful.
Java Programming 50
4. A nested class can have private, public, protected, or the default access, just like any member variables
and methods defined inside a class. A private inner class is only accessible by the enclosing outer class, and is
not accessible by any other classes. [An top-level outer class cannot be declared private, as no one can use a
private outer class.]
5. A nested class can also be declared static, final or abstract, just like any ordinary class.
6. A nested class is NOT a subclass of the outer class. That is, the nested class does not inherit the
variables and methods of the outer class. It is an ordinary self-contained class. [Nonetheless, you could declare
it as a subclass of the outer class, via keyword "extends OuterClassName", in the nested class's definition.]
1. To control visibilities (of the member variables and methods) between inner/outer class. The nested
class, being defined inside an outer class, can access private members of the outer class.
2. To place a piece of class definition codes closer to where it is going to be used, to make the program
clearer and easier to understand.
import java.awt.*;
import java.awt.event.*;
public class InnerClassDemo extends Frame {
private TextField tfCount;
private Button btnCount;
private int count = 0;
setVisible(true);
}
// The entry main method
public static void main(String[] args) {
new InnerClassDem (); // Let the constructor do the job
}
/* BtnCountListener is a "named inner class" used as ActionListener. This inner class can access private
variables of the outer class. */
private class BtnCountListener implements ActionListener {
• An anonymous instance of the BtnCountListener inner class is constructed. The btnCount source object
adds this instance as a listener, as follows:
btnCount.addActionListener(new BtnCountListener());
• The inner class can access the private variable tfCount and count of the outer class.
import java.awt.*;
import java.awt.event.*;
setTitle("AWT Counter");
setSize(250, 100);
setVisible(true);
}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
Hierarchy of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Java Programming 54
The java.applet.Applet class provides 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
[ALIGN = alignment]
>
...
</APPLET>
CODEBASE :
CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the
directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML
document’s URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does
not have to be on the host from which the HTML document was read.
CODE :
It is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is
relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory
indicated by CODEBASE if set.
ALT :
The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser
recognizes the APPLET tag but can’t currently run Java applets. This is distinct from the alternate HTML you
provide for browsers that don’t support applets.
NAME :NAME is an optional attribute used to specify a name for the applet instance.Applets must be named in
order for other applets on the same page to find them by name and communicate with them. To obtain an applet
by name, use getApplet( ), which is defined by the AppletContext interface.
WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.
ALIGN:
ALIGN is an optional attribute that specifies the alignment of the applet. The possible values: LEFT, RIGHT,
These attributes are optional. VSPACE specifies the space, in pixels,bove and below the applet. HSPACE
specifies the space, in pixels, on each side of the applet.
The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their
attributes with the getParameter( ) method.
Other valid APPLET attributes include ARCHIVE, which lets you specify one or more archive files, and
OBJECT, which specifies a saved version of the applet.
Note:
APPLET tag should include only a CODE or an OBJECT attribute, but not both.
Applet classes need to be declared as a public becomes the applet classes are access from HTML document
that means from outside code. Otherwise, an applet will not be accessible from an outside code i.e an HTML
Running an Applet
1. By html file.
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome",150,150);
}
Java Programming 57
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
<html>
<body>
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it.
After that run it by: appletviewer Filename.java. Now Html file is not required but it is for testing purpose only.
Example:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome to applet",150,150);
c:\>javac First.java
c:\>appletviewer First.java
Java Programming 58
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example
of event handling in applet that prints a message by click on the button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
tf.setText("Welcome");
}
Java Programming 59
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
</applet>
</body>
</html>
In order for Java to enable applets to be downloaded and executed on the client computer safely, it was
necessary to prevent an applet from launching such an attack.Java achieved this protection by confining an
applet to the Java execution environmentand not allowing it access to other parts of the computer. The ability to
download applets with confidence that no harm will be done and that no security will be breached is considered
by many to be the single most innovative aspect of Java
Advantages of Applets:
1. Execution of applets is easy in a Web browser and does not require any installation or deployment
procedure in realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not required (but are
required in applications).
Restrictions of Applets:
2. In realtime environment, the bytecode of applet is to be downloaded from the server to the client
machine.
3. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown
servers whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure,
to access any system resources like file system etc. available on the client system.
cannot access any thing on the system except Can access any data or software
Restrictions browser’s services available on the system
Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
Execution JAVA supported browser machine
Example: Example:
Example
Java Programming 61
import java.applet.*; {
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter().
Syntax:
import java.applet.Applet;
import java.awt.Graphics;
String str=getParameter("msg");
g.drawString(str,50, 50);
myapplet.html
<html>
<body>
</applet>
</body>
</html>
We can even create applets based on the Swing package. In order to create such applets, we must extend
JApplet class of the swing package. JApplet extends Applet class, hence all the features of Applet class are
available in JApplet as well, including JApplet's own Swing based features. Swing applets provides an easier to
use user interface than AWT applets.
When we creat an AWT applet, we implement the paint(Graphics g) method to draw in it but when we
create a Swing applet, we implement paintComponent(Graphics g) method to draw in it.
For an applet class that extends Swing's JApplet class, the way elements like textfield, buttons,
checksboxes etc are added to this applet is performed by using a default layout manager, i.e.
BorderLayout.
Swing applets use the same four lifecycle methods: init( ),start( ), stop( ), and destroy( ). Of course, you need
override only those methods that are needed by your applet. Painting is accomplished differently in Swing than
it is in the AWT,and a Swing applet will not normally override the paint( ) method.
Java Programming 63
In this example , first, we have created a swing applet by extending JApplet class and we have added a JPanel to
it.Next, we have created a class B, which has extended JPanel class of Swing package and have also
implemented ActionListener interace to listen to the button click event generated when buttons added to JPanel
are clicked.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="SwingAppletDemo" width="500" height="200">
</applet>
*/
public class SwingAppletDemo extends JApplet
{
public void init()
{
add(new B()); //Adding a JPanel to this Swing applet
}
}
B( )
{
jb= new JLabel("Welcome, please click on button to unbox some interesting knowledge -");
box1 = new JButton("Box1");
str ="";
setLayout(new FlowLayout());
add(jb);
add(box1);
box1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Java Programming 64
if(ae.getActionCommand().equals("box1"))
{
str=" welcome to SwingApplet programming";
repaint();
}
}
Syntax:
To cause a component to be painted under program control, call repaint( ). It works in Swing just as it does for
the AWT. The repaint( ) method is defined by Component. Calling it causes the system to call paint( ) as soon
Java Programming 65
as it is possible to do so. In Swing the call to paint( ) results in a call to paintComponent( ). Inside the
overridden paintComponent( ), you will draw the stored output
5.3.7 Exploring Swing Controls- JLabel , Image Icon and JText Field
JLabels
Image Icon
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
JTextField
A JTextField is an area that the user can type one line of text into. It is a good way of getting text
public JTextField (int columns) // create text field with appropriate # of columns
public JTextField (String s, int columns) // create text field with s displayed & approp.
width
Methods include:
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
Methods Description
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Question:
subclasses of JButton class.[2 marks]
Subclasses:
1.BasicArrowButton,
2.MetalComboBoxButton
1.BasicArrowButton:
Constructors:
BasicArrowButton(int direction); --Creates a BasicArrowButton whose arrow is drawn in the specified
direction.
Java Programming 70
BasicArrowButton(int direction, Color background, Color shadow, Color darkShadow, Color highlight)--
Creates a BasicArrowButton whose arrow is drawn in the specified direction and with the specified
colors.
2.MetalComboBoxButton
Constructors :
MetalComboBoxButton(JComboBox cb, Icon i, boolean onlyIcon, CellRendererPane pane, JList list)
JToggle Button
Auseful variation on the push button is called a toggle button. A toggle button looks just like a push
button, but it acts differently because it has two states: pushed and released. That is, when you press
a toggle button, it stays pressed rather than popping back up as a regular push button does. When you
press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is
JToggleButton constructors:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the button is in the off position.
Other constructors enable you to create toggle buttons that contain images,or images and text.
To handle item events, you must implement the ItemListener interface.Each time an item event is generated, it
is passed to the itemStateChanged( )method defined by ItemListener. Inside itemStateChanged( ), the getItem(
) method canbe called on the ItemEvent object to obtain a reference to the JToggleButton instance
thatgenerated the event. It is shown here:
Object getItem( )
A reference to the button is returned. You will need to cast this reference to JToggleButton.The easiest way to
determine a toggle button’s state is by calling the isSelected( ) method(inherited from AbstractButton) on the
button that generated the event. It is shown here:
boolean isSelected( )
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
Java Programming 72
add(jlab);
}
}
The output from the toggle button example is shown here:
JCheck Box
The JCheckBox 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 ".It inherits JToggleButton class.
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is initially
selected) selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.
Methods Description
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
Java Programming 74
JRadio Button
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options.
It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
Methods Description
import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
Java Programming 76
JTabbed Pane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with tabs. Selecting a
tab causes the component associated with that tab to come to the forefront.
JTabbedPane defines three constructors. We will use its default constructor, whichcreates an empty control with
the tabs positioned across the top of the pane. The other two constructors let you specify the location of the tabs,
which can be along any of the foursides. JTabbedPane uses the SingleSelectionModel model.Tabs are added by
calling addTab( ). Here is one of its forms:
Here, name is the name for the tab, and comp is the component that should be added to the tab. Often, the
component added to a tab is a JPanel that contains a group of related components. This technique allows a tab to
hold a set of components
In this exampleThe first tab is titled “Cities” andcontains four buttons. Each button displays the name of a city.
The second tab is titled“Colors” and contains three check boxes. Each check box displays the name of a color.
The third tab is titled “Flavors” and contains one combo box. This enables the user to select oneof three flavors.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
Java Programming 77
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
Java Programming 78
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Output:
Java Programming 79
JScroll Pane
JScrollPane is a lightweight container that automatically handles the scrolling of another component. The
component being scrolled can either be an individual component, such as a table, or a group of components
contained within another lightweight container, such as a JPanel
JScrollPane defines several constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically displayed when the content of
the pane exceeds the dimensions of the viewport.
First, a JPanel object is created, and 400 buttons are added to it, arranged into 20 columns. This panel is then
added to a scroll pane,and the scroll pane is added to the content pane. Because the panel is larger than the
viewport, vertical and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the
buttons into view.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
Java Programming 80
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
Output:
Java Programming 81
JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user can
choose either one item or multiple items. It inherits JComponent class.
Constructor Description
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
Methods Description
Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified each time a
listener) change to the selection occurs.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
Java Programming 82
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
Output:
Java Programming 83
JCombo Box
Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox
class. A combo box normally displays one entry, but it will also display a drop-down list that allows a user to
select a different entry.
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box. Other constructors are available.JComboBox uses the
ComboBoxModel. Mutable combo boxes (those whose entries canbe changed) use the
MutableComboBoxModel.
In addition to passing an array of items to be displayed in the drop-down list, items canbe dynamically added
to the list of choices via the addItem( ) method, shown here:
Here, obj is the object to be added to the combo box. This method must be used only withmutable combo
boxes.
One way to obtain the item selected in the list is to call getSelectedItem( ) on the combobox. It is shown here:
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in the list.
The following example demonstrates the combo box. The combo box contains entries for “France,”
“Germany,” “Italy,” and “Japan.” When a country is selected, an icon-based label is updated to display the flag
for that country. You can see how little code is required to use this powerful component.
// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
Java Programming 84
</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Instantiate a combo box and add it to the content pane.
jcb = new JComboBox(flags);
add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.
jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
Java Programming 85
Output:
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the
JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the
JMenuItem or any of its subclass.
Dialogs
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input
dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits
JComponent class.
Constructor Description
JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a message with specified
messageType message type and default options.
Methods Description
static void showMessageDialog(Component parentComponent, It is used to create a message dialog with given title
Object message, String title, int messageType) and messageType.
static int showConfirmDialog(Component parentComponent, It is used to create a dialog with the options Yes, No
Object message) and Cancel; with the title, Select an Option.
import javax.swing.*;
JFrame f;
OptionPaneExample(){
f=new JFrame();
new OptionPaneExample();
Output:
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Java Programming 89
Output:
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
Swing Applet
Swing have look and feel according to user view you Applet Does not provide this facility.
can change look and feel using UIManager.
Swing uses for stand lone Applications, Swing have Applet need HTML code for Run the Applet.
main method to execute the program.
Swing have its own Layout like most popular Box Applet uses AWT Layouts like flowlayout.
Layout.
Swing have some Thread rules. Applet doesn't have any rule.
To execute Swing no need any browser By which we To execute Applet programe we should need any one
can create stand alone application But Here we have to browser like Appletviewer, web browser. Because
add container and maintain all action control with in Applet using browser container to run and all action
frame container. control with in browser container.
Java Programming 91
1a) What is the significance of layout managers? Discuss briefly various layout managers.
b) Give an overview of JButton class. [5+5]
4a) Write a Java program to create AWT radio buttons using check box group.
b) Explain the various event listener interfaces. [5+5]
7. Write a program to demonstrate various keyboard events with suitable functionality. [10]
10.a) What is the role of event listeners in event handling? List the Java event listeners
b) Write an applet to display the mouse cursor position in that applet window.[5+5]
12.a) What is an applet? Explain the life cycle of Applet with a neat sketch.
b) Write the applets to draw the Cube and Cylinder shapes. [5+5]
15.a) Create a simple applet to display a smiley picture using Graphics class methods.
b) Write a short note on delegation event model. [5+5]
16 a) List and explain different types of Layout managers with suitable examples.
b) How to move/drag a component placed in Swing Container? Explain. [5+5]
18 a) What is the difference between init( ) and start ( ) methods in an Applet? When will each be
executed?
b) Write the applets to draw the Cube and Circle shapes. [5+5]