Multithreading: Object Oriented Programming 1
Multithreading: Object Oriented Programming 1
UNIT
4
MULTITHREADING
Syllabus:
Multi Threading: java.lang.Thread, The main Thread, Creation of new threads,
Thread priority, Multithreading – Using isAlive() and join(), Synchronization,
suspending and resuming threads, Communication between Threads.
Input/Output: reading and writing data, java.io package
4.2 Multitasking: -
All modern operating systems support the concept of multitasking. Multitasking is
the feature that allows the computer to run two or more programs concurrently.
CPU scheduling deals with the problem of deciding for which of the process, the
ready queue is to be allocated. It follows CPU(Processor) scheduling algorithms.
The priority scheduling follows on Sun Solaris systems. But it doesn’t work on the
present operating systems like windows NT etc., The thread with a piece of system
code is called the thread scheduler. It determines which thread is running actually
in the CPU.
The Solaris java platform runs a thread of given priority to completion or until
a higher priority thread becomes ready at that point preemption occurs.
b) Round-Robin Scheduling:
Note:
1. Java provides built-in support for multithreaded programming
2. Java multithreading is a platform independent
3. Elimination of main loop is the main benefit of multithreaded
programming.
4.3 Thread States (Life-Cycle of a Thread)
The life cycle of a thread contains several states. At any time the threads is falls into
any one of the states.
At any time a thread is said to be in one or more states.
Java language has two keywords related to the threads. Volatile and synchronized.
Both of these keywords help ensure the integrity of data that is shared between two
concurrently running threads.
Run( ) method:
The run( ) method is available both in Thread class and Runnable interface. We can
subclass a Thread class and override the run( ) method. We write the specific code,
which we would like to do by the thread, in the run( ) method. Run( ) method is the
heart of any Thread. Run( ) method is called implicitly by the start ( ) method.
In java, we can create threads in two ways – one by sub classing the Thread class
and one by implementing Runnable interface.
sleep( ) method:
Sleep( ) is a method of Thread class with the following syntax
Public static void sleep(long milliseconds) throws InterruptedException
Sleep() method is static and throws a checked exception, InterruptedException.
Sleep() method, we should take care of InterruptedException by providing try catch
block. Sleep( ) method makes a running(active) thread not to run(inactive) for the
specified milliseconds of time. When the sleep time expires, the thread becomes
automatically active. The active thread executres the run( ) method.
When the thread comes out of the run( ) method, it dies.
start( ) method:
UsingThread ut=new UsingThread();
Ut.start( );
In the above first statement, a thread by name ut is created. The thread ut is in
born state and is inactive. The inactive thread cannot call run() method. The thread
is born state occupies the memory resources but cannot take microprocessor time.
In the second statement, we call the start( ) method on the thread. Start( ) method
implicitly calls run( ) method. The thread in run state is active and utilizes
microprocessor time.
4.11 Synchronization:
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization. As you will see, java provides
unique language level support for it. Key to synchronization is the concept of the
monitor (also called a semaphore) a monitor is an object that is used as mutually
exclusive lock or mutex. Only one thread can own a monitor at a object that is used
as mutually exclusive lock or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock it is said to have entered the monitor. All other
threads attempting to enter the locked monitor will be suspended until the first
thread exists the monitor. These other threads are said to be waiting for the
monitor. A thread get own a monitor can reenter the same monitor if it so desires.
Program 7: // This program is not synchronized
class callme
{
void call(String msg)
{
System.out.println(“[ “+msg);
try
UNIT
5&6
APPLETS,
EVENT
HANDLING,
AWT & SWING
Syllabus:
Applets – Applet class, Applet structure, An Example Applet Program, Applet Life
Cycle, paint(), update() and repaint()
Event Handling – Introduction, Event Delegation Model, java.awt.event,
Description, Sources of Events, Event Listeners, Adapter classes, Inner classes
AWT : Why Awt? Java.awt package, Components and Containers, Button, Label,
Checkbox, Radio buttons, List boxes, Choice boxes, Text Field and Text Area,
container classes, Layouts, Menu, Scroll bar
Swing : Introduction, JFrame, JApplet, JPanel, Components in swings, Layout
Managers, JList and JScroll Pane, Split Pane, JTabbedPane, Dialog box, Pluggale
Look and feel
CheckboxGroup
MenuComponent
LayoutManager
Ex:
import java.awt.*;
import java.applet.*;
/*<applet code=ap width=200 height=200></applet>*/
public class ap extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello ramesh !",80,30);
Color Class:
The Class Color defines methods and constants for manipulating colors in a java
program. The predefined constants are
Color.black, Color.magneta, Color.blue, Color.orange, Color.cyan, Color.pink,
Color.drakGray, Color.red, Color.gray, Color.white, Color.green, Color.yellow,
Color.lightGray.
The constructors are
Color(int red, int green, int blue)
Color(int rgb value)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red,
green, and blue. These values must be between 0 and 255.
The second constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23,
green in bits 8 to 15, and blue in bits 0 to 7.
The final constructor takes three float values (between 0.0 to 1.0) that specify that
relative mix of red, green, and blue.
You can change the color by calling the Graphics method
setColor(Color newColor)
You can obtain the current color by calling method getColor()
Color getColor( )
Ex:
import java.awt.*;
import java.applet.*;
/*<applet code=ap width=200 height=200></applet>*/
public class ap extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(220,185,135);
Color c2=new Color(200,178,230);
Color c3=new Color(150,220,234);
g.setColor(c1);
g.drawString("Hello ramesh !",80,30);
g.setColor(c2);
You can use FontMetrics to compute the exact length and width of a string, which
is helpful for measuring string size in order to display it in the right position. A
FontMetrics is measured by the following attributes:
Leading-Pronounced ledding, this is the amount of space between lines of
text.
Ascent – This the height of a character, from the baseline to the top.
Descent – This is the distance from the baseline to the bottom of a
descnding character, such as j,y, and g.
import java.applet.*;
import java.awt.*;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font1 width=400 height=400></applet>*/
public class font1 extends JApplet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
int k=12,y=50;
for(int i=0;i<s1.length();i++)
{
g.setFont(new Font("Times New Roman",Font.BOLD,k));
g.drawString(s1,125,y);
y=y+35;
k=k+5;
}
}
}
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font3 width=400 height=400></applet>*/
public class font3 extends Applet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
int k=15,x=100;
for(int i=0;i<s1.length();i++)
{
g.setFont(new Font("Times New Roman",Font.PLAIN,k));
g.drawString(String.valueOf(s1.charAt(i)),x,100);
x=x+35;
k=k+5;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font4 width=400 height=400></applet>*/
public class font4 extends Applet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
for(int i=2,col=300,row=20;row<=500;i+=10,col-=20,row+=(40+i-10))
{
g.setFont(new Font("Arial",Font.BOLD,i));
g.drawString(s1,col,row);
}
}
}
Drawing Lines:
You can draw a straight line by using the following method:
drawLine(x1, y1, x2, y2);
The components (x1,y1) and (x2,y2) are the starting and ending points of the line.
(x1,y1)
(x2,y2)
(x, y) W
To draw a rounded rectangle filled with color, use the following code:
fillRoundRect(x, y, w, h, aw, ah);
The component x, y, w and h are the same as in the drawRect() method, the
parameter aw is the horizontal diameter of the arcs at the corner, and ah is the
vertical diameter of the arcs at the corner.
(x, y) W
ah
(x, y) W
Arcs:
Like an oval, an arc is drawn based on its bounding rectangle. An arc is conceived
as part of an oval. The syntax to draw or fill an arc is as follows:
drawArc(x, y, w, h, angle1, angle2);
fillArc(x, y, w, h, angle1, angle2);
The components x, y, w and h are the same as in the drawOval( )method; the
parameter angle1 is the starting angle; angle2 is the spanning angle(that is, the
ending angle is angle1+angle2). Angles are measured in degree and follow the usual
mathematical conventions(that is, 0 degree is at 3’o clock, and positive angles
indicate counterclockwise rotation)
Polygons:
The Polygon class encapsulates a description of a closed, two-dimensional region
with a coordinate space. This region is bounded by a arbitrary number of lines
segments, each of which is one side(or edge) of the polygon. A polygon comprises a
list of (x, y) corrdinate pairs, in which each pair defines a vertex of the polygon, and
two successive pairs are the end points of a line that is a side of the polygon. The
first and final pairs of (x, y) points are joined by a line segment that closes the
polygon.
drawPolygon(x, y, n);
fillPolygon(x, y, n);
The components x and y are arrays of x-coordinates and y-coordinates, and n
indicates the number of points.
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=line1 width=400 height=400></applet>*/
public class line1 extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<400;i+=10)
{
g.drawLine(0,i,400,i);
g.drawLine(i,0,i,400);
}
}
}
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=line2 width=400 height=400></applet>*/
public class line2 extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<400;i+=10)
{
g.drawLine(0,i,i,0);
g.drawLine(400,i,i,400);
}
for(int j=0;j<=400;j+=10)
{
g.drawLine(j,0,400,400-j);
g.drawLine(0,j,400-j,400);
}
import java.awt.*;
import javax.swing.*;
/*<applet code=draw width=400 height=500></applet>*/
public class draw extends JApplet
{
public void paint(Graphics g)
{
for(int i=1;i<=25;i++)
g.drawLine(10,10,250,i*10);
}
}
import java.awt.*;
import javax.swing.*
/*<applet code=circle width=300 height=300></applet>*/
public class circle extends JApplet
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=fish width=600 height=250></applet>*/
public class fish extends Applet
{
public void paint(Graphics g)
{
g.drawArc(100,100,300,100,15,155);
g.drawArc(100,100,300,100,155,345);
g.drawOval(110,140,10,10);
g.drawArc(100,144,30,15,180,180);
for(int i=125;i<350;i+=25)
g.drawArc(i,122,50,75,45,45);
for(int i1=120;i1<350;i1+=25)
g.drawArc(i1,150,50,75,45,45);
for(int i2=125;i2<350;i2+=25)
g.drawArc(i2,175,50,75,45,45);
g.drawArc(400,100,150,100,180,90);
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=lamp width=600 height=250></applet>*/
public class lamp extends Applet
{
public void paint(Graphics g)
{
g.drawArc(100,100,146,100,176,199);
g.drawArc(100,105,145,70,185,178);
g.drawOval(158,88,25,85);
g.fillRect(100,200,150,50);
}
}
Event-Driven Programming:
Java graphics programming is event driven. In event-driven programming, the
codes are executed upon activation of events. This section introduces the java
event model
Event and Event Source:
When you are writing programs using the AWT, the program interacts with
the user and the events drive the execution of the program. An event can be
defined as a type of signal to the program that something has happended. The
event is generated by external user actions such as mouse movements, mouse
button clicks, and keystrokes, or by the operating system, such as a timer. The
program can choose to respond or ignore the event.
The GUI component on which the event is generated is called a source object.
For example, clicking a button triggers an event. The button is the souce object,
The source object can be obtained by using the getSource() method. Every event is a
subclass of the AWTEvent class. Various types of AWT events deal with user
component actions, mouse movement, and keystrokes. For convenience, all the
AWT event classes are included in the java.awt.event package.
An event is triggered when a user clicks over a component. The mechanism
being used to generate and handle the events (to execute the code for which the
event is meant) is called as Event Handling Mechanism. In 1.0 version of JDK, it is
known as Hierarchical – Event Model handling and in JDK1.1 on wards it is known
as Delegation-Event Model Handling.
Delegation Event Handling Mechanism:
Step 1: Import the event package
All the interfaces and classes required fro event handling are included by the
jaa designers in the package java.awt.even package(it is a subpackage of java.awt
TextEvent WindowEvent
Event Object
User
Action Generating an event
Notify Listener
Triggering an event
Listener Object
Source Object
Event Handler
Register a listener object
AWT Components:
Label:
Methods:
public getText()
This returnsa string for the label.
public setText(String s)
This changes the text string of the label.
public getAlignment( )
This returns the alignment of the label.
public setAlignment(int Alignment)
This resets the alignment of the label.
Button:
A button is a component that triggers an event when pressed.
public Button()
This creates an empty button with no label.
public Button(String s)
This creates a button labeled with the specified string.
Methods:
public String getLabel( )
This returns the label of a button
Public void setLabel(String str)
This changes the label of the button with the new specified string str
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*<applet code=car width=400 height=400></applet>*/
public class car extends Applet implements ActionListener
{
Label l1;
Button b1,b2;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
TextField:
A textfield is an input area where the user can type in characters. Text fields are
useful in that they enable the user to enter in variable data (a name or a
description)
The constructors are
public TextField(int width)
This creates an empty text field with the specified number of columns
Public TextField(String s)
This creates a text field initialized with the specified string s
Public TextField(String s, int width)
This creates a textfield initialized with the specififed string s and the column size
width.
Methods:
public String getText()
This returns the string from the text field.
public void setText(String s)
This puts the given string in the text field.
public void setEditable(boolean editable)
This enables or disables the textfield to be edited. By default, editable is true.
public void setColumns (int)
This sets the number of columns in this text field. The length of the text filed is
changeable.
TextField might generate ActionEvent and ItemEvent. Pressing return on a
text field triggers the ActionEvent. Changing contents on a text filed triggers the
ItemEvent.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=text1 width=400 height=400></applet>*/
public class text1 extends Applet implements ActionListener
TextArea:
If you want to let the user enter multiple lines of text, you can’t use TextField unless
you create several of them. The solution is to use TextArea, which enables the user
to enter multiple lines of text.
Checkbox:
A Checkbox is a component that enables the user to toggle a choice on or off, like
a light switch.
The constructors are
public Checkbox()
public Checkbox(String label)
public Checkbox(String label,Boolean on)
The first form creates a checkbox whose label is initially blank. The state of
the checkbox is unchecked. The second form creates a checkbox whos lable is
specifid by label. The state of the check box is unchecked. The third form allows
you to set the initial state of the checkbox. If on is true, the checkbox is initially
checked; otherwise, it is cleared.
To retrieve the current state of a checkbox, call getState(), To set its state, call
setState(). You can obtain the current label associated with a check box by calling
getLabel(). To set the label, call setLabel()
Boolean getState()
Void setState(Boolean on)
String getLabel()
Void setLabel(String str)
CheckboxGroup:
Checkbox groups, also known as option buttons, are variations of check boxes, but
only one box in the group can be checked at a time. Its appearance is similar to a
check box. Check boxes display a square that is either checked or blank, and a
check box in the group displays a circle that is either filled( if selected) or blank( not
selected).
The constructor are
CheckboxGroup cgb=new CheckboxGroup();
This creates the CheckboxGroup object cgb.
Checkbox cb1;
add(cb1=new Checkbox(“Choice name 1”,cgb,true));
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=text width=400 height=400></applet>*/
public class text extends Applet implements ItemListener
{
Checkbox c1,c2,c3,c4;
CheckboxGroup cb;
public void init()
{
cb=new CheckboxGroup();
c1=new Checkbox("Windows 98",cb,false);
c2=new Checkbox("Windows NT",cb,false);
c3=new Checkbox("Windows Xp ",cb,true);
c4=new Checkbox("Linux ",cb,false);
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
Choice:
A choice is a simple list of items from which the user can choose. It’s useful in
limiting a user’s range of choices and avoids the cumbersome validation of data
input. You can easily choose and extract the value in a choice box.
The constructors are
public Choice( )
This creates a Choice component.
Methods:
public void addItem(String s)
This adds the item s into the choice.
public String getItem(int index)
This gets an item from the choice at the specified index.
public int getSelectedIndex( )
This gets the index of the selected item.
public String getSelectedItem( )
This gets the selected item.
public void select(int pos)
This selects the item with the specified position.
public void select(String str)
List:
A List is a component that performs basically the same function as a Choice, but it
enables the user to choose a single value or multiple values.
public List(int rows, boolean multipleselection)
This creates a new scrolling list with the specified number of visible rows and the
parameter multipleselection indicates whether multiple selection is eabled.
public List(int rows)
This creates a new single selection scrolling list initialized with the specified number
of visible rows.
public List()
This creates a new scrolling list initialized with no visible lines or multiple
selections.
Methods:
public void addItem(String s)
Adds the item s into the list.
public String getItem(int row)
This gets an item from the list at the specified row.
public int getSelectedIndex( )
This gets the index of the selected item
public String getSelectedItem()
This gets the selected item
Public String[ ] getSelecteditems()
This returns an array of strings containing the selected items.
List may generate ActionEvent and ItemEvent. Clicking a list item triggers the
ItemEvent. To trigger the ActionEvent, you need to double-click the selected item.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*<applet code=choice width=400 height=400></applet>*/
public class choice extends Applet implements ItemListener
{
Choice c2;
List l1;
public void init()
{
Scrollbar: - Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or vertically. A
scroll bar is actually a composite of several individual parts. Each end has an arrow
that you can click to move the current value of the scroll bar one uit in the direction
of the arrow. The current value of the scroll bar relative to its minimum and
maximum values is indicated by the slider box(or thumb) for the scroll bar. The
Point Constructor:
Point(int x,int y)
This constructs a Point object with the specified x and y coordinates.
You can use the move(int x,int y) method to move the point to the specified x and y
coordinates.
MouseEvent Methods:
public int getClickCount( )
This returns the number of mouse clicks associated with this event.
public Point getPoint( )
This returns the x-and y-coordinates of the event relative to the source component.
public int getX( )
This returns the x-coordinate of the event relative to the source component.
public int getY( )
This returns the y-corrdinate of the event relative to the source component.
The MouseEvent class inherits InputEvent. You can use the methods define in the
InputEvent class on a MouseEvent object.
InputEvent Methods:
public long getWhen( )
This returns the time stamp of when this event occurred.
public boolean isAltDown( )
This returns whether the Alt modifier is down on this event.
public boolean isControlDown( )
This returns whether the Control modifer is down on this event.
public boolean isMetaDown( )
This returns whether the Meta modifier is down on this event.
public boolean isShiftDown( )
This returns whether the Shift modifier is down on this event.
Key Constants:
Constant Description
VK_HOME The Home key
VK_END The End key
VK_PGUP The Page Up key
VK_PGDN The Page Down key
VK_UP The Up arrow key
VK_DOWN The down arrow key
VK_LEFT The left arrow key
VK_RIGHT The right arrow key
VK_ESCAPE The Esc key
VK_TAB The tab key
VK_BACK_SPACE The backspace key
VK_CAPS_LOCK The Caps lock key
VK_NUM_LOCK The Num lock key
VK_ENTER The Enter key
VK_F1 to VK_F12 The function keys f1 to f12
VK_0 to VK_9 The number keys from 0 to 9
VK_A to VK_Z The letter keys from A to Z
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class key extends Frame implements KeyListener
{
public key()
{
super("Using Key Events ");
addKeyListener(this);
setSize(200,200);
setVisible(true);
}
public void keyPressed(KeyEvent e){ }
public void keyReleased(KeyEvent e){ }
public void keyTyped(KeyEvent e)
{
char ch=e.getKeyChar();
if(ch=='r')
setBackground(Color.red);
else
if(ch=='R')
setBackground(Color.red);
else
if(ch=='g'||ch=='G')
setBackground(Color.green);
else
if(ch=='b')
setBackground(Color.blue);
else
if(ch=='m')
setBackground(Color.magenta);
else
if(ch=='c')
setBackground(Color.cyan);
else
System.out.println("type only r,g,b,c,m only");
}
public static void main(String arg[])
{
new key();
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=keyevent width=400 height=400></applet> */
public class keyevent extends Applet implements KeyListener
{
int x=100,y=100;
char ch='A';
public void init()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_DOWN:y+=10;break;
case KeyEvent.VK_UP:y-=10;break;
case KeyEvent.VK_LEFT:x-=10;break;
case KeyEvent.VK_RIGHT:x+=10;break;
default:ch=e.getKeyChar();
}
repaint();
}
public void paint(Graphics g)
{
g.setFont(new Font("Times New Roman",Font.BOLD,24));
g.drawString(String.valueOf(ch),x,y);
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=mouse1 width=400 height=400></applet>*/
public class mouse1 extends Applet
{
int x=0,y=0,x1=0,y1=0;
public void init()
{
addMouseListener(new adapter1());
addMouseMotionListener(new adapter2());
}
GridLayout:
The GridLayout manager arranges componets in a grid(matrix) formation with the
number of rows and columns defined by the constructor. The components are
placed in the grid from left to right starting with the first row, then the second, and
so on, in the order in which they are added.
Constructors:
Public GridLayout(int rows, int columns)
This constructs a new GridLayout with the specified number of rows and columns.
Public GridLayout(int rows, int columns, int hgap, int vgap)
This constructs a new GridLayout with the specified number of rows and columns,
along with specified horizontal and vertical gaps between components.
BorderLayout:
The BorderLayout manager divides the window into five areas: East, South, West,
North and Center. Components are added to a BorderLayout by using
add(String,Component), Where String is “East”,”South”,”West”,”North” or “Center”.
Constructors:
Public BorderLayout(int hgap, int vgap)
This constructs a new BorderLayout with the specified horizontal and vertical gaps
between the components.
Public BorderLayout()
This constructs a new BorderLayout without horizontal or vertical gaps.
The components are laid out according to their preferred sizes and the constraints
of the container’s size. The North and South components can be stretched
gridx and gridy: - Specifies the cell at the upper left of the component’s display area,
where the upper-left-most cell has address gridx=0, gridy=0. Note that gridx
Panels:
Suppose that you want to place 10 buttons and a text field on a frame. The buttons
are placed in grid formation, but the text field is placed on a separate row. It is
difficult to achieve the desired look by placing all the components using a single
container. With AWT programming, imagine dividing a window into panels. Panels
act as smaller containers for grouping user interface components. You can add the
butons in one panel and the text fields in another and then add the panels into the
frame.
Constructor:
Panel p= new Panel( );
By default, panels use FlowLayout.
Canvases:
Menu:
Menus make selection easier, and are widely used in window applications. In Java,
menus can only appear on a frame. Java provides three classes-MenuBar, Menu
and MenuItem – to implement menus in a frame.
A frame can hold a menubar to which the pull-down menus are attached. Menus
consist of menu items that the user can select (or toggle on or off). Menu baras can
be viewed as a structure to support menus.
1. Create a menu bar and associate in with a frame.
Frame f=new Frame( );
f.setSize(300,200);
f.setVisible(true);
MenuBar mb=new MenuBar( );
f.setMenuBar(mb);
This code creates a frame and a menu bar, and sets the menu bar in the frame.
2. Create menus
You can use the following constructors to create a menu.
public Menu(String label, boolean f)
This constructs a new Menu instance with the specified label and f. The true f
enables the programmer to create a menu that displays even when the mouse
button is released.
public Menu(String label)
This constructs a new menu instance with the specified label. It is equivalenet to
Menu(label,false)
The character “-“ separates menu items. You may also use the addSeparator()
method to separate menu items.
F1.addSeparator( )
import java.awt.*;
import java.awt.event.*;
public class menu1 extends Frame implements ActionListener
{
MenuBar m;
Menu m1,m2,m3,m4;
MenuItem mm1,mm2,mm3,mm4,mm5,mm6,mm7,mm8,mm9,mm10;
String s=" ";
public menu1( )
{
setTitle(" Sample menu ");
The original GUI components from the Abstract Windowing Toolkit package
java.awt (also called the AWT) are tied directly to the local platform’s graphical user
interface capabilities. So, a java program executing on different java platforms has a
different appearance and sometimes even different user interactions on each
platform. The appearance and how the user interacts with the program are known
as that program look and feel. The Swing components allow the programmer to
specify a different look and feel for each platform, or a uniform look and feel across
all platforms, or event to change the look-and-feel while the program is running.
JRootPane
class javax.swing.JRootPane
Each JRootPane contains several components referred to here by variable name:
The menuBar does not exist by default but can be set by calling the
setJMenuBar() method:
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);
RootLayout
class javax.swing.JRootPane.RootLayout
RootLayout is a layout manager built specifically to manage JRootPane’s
layeredPane, glassPane, and menuBar. If it is replaced by another layout manager
that manager must be able to handle the positioning of these components.
RootLayout is an inner class defined within JRootPane and as such, is not intended
to have any use outside of this class. Thus it is not discussed in this text.
The RootPaneContainer interface
abstract interface javax.swing.RootPaneContainer
The purpose of the RootPaneContainer interface is to organize a group of methods
that should be used to access a container’s JRootPane and its different panes (see
API docs). Because JFrame‘s main container is a JRootPane, it implements this
interface (as does JFrame and JDialog). If we were to build a new component which
uses a JRootPane as its main container we would most likely implement the
RootPaneContainer interface. (Note that this interface exists for convenience,
consistency, and organizational purposes. We are encouraged to, but certainly not
required to, use it in our own container implementations.)
The WindowConstants interface
abstract interface javax.swing.WindowConstants
We can specify how a JFrame, JInternalFrame, or JDialog acts in response to the
user closing it through use of the setDefaultCloseOperation() method. There are
three possible settings, as defined by WindowConstants interface fields:
WindowConstants.DISPOSE_ON_CLOSE
WindowConstants.DO_NOTHING_ON_CLOSE
WindowConstants.HIDE_ON_CLOSE
The names are self-explanatory. DISPOSE_ON_CLOSE disposes of the JFrame and
its contents, DO_NOTHING_ON_CLOSE renders the close button useless, and
HIDE_ON_CLOSE just removes the container from view. (HIDE_ON_CLOSE may be
useful if we may need the conatiner, or something it contains, at a later time but do
not want it to be visible until then. DO_NOTHING_ON_CLOSE is very useful as you
will see below.)
The WindowListener interface
abstract interface java.awt.event.WindowListener
Classes that want explicit notification of window events (such as window closing,
iconification, etc.) need to implement this interface. Normally the WindowAdapter
WindowEvent
class java.awt.event.WindowEvent
The type of event used to indicate that a window has changed state. This
event is passed to every WindowListener or WindowAdapter object which is
registered on the source window to receive such events. Method getWindow()
returns the window that generated the event. Method paramString() retreives a
String describing the event type and its source, among other things.
There are six types of WindowEvents that can be generated; each is
represented by the following static WindowEvent fields: WINDOW_ACTIVATED,
WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_DEACTIVATED,
WINDOW_DEICONIFIED, WINDOW_ICONIFIED, WINDOW_OPENED.
WindowAdapter
abstract class java.awt.event.WindowAdapter
This is an abstract implementation of the WindowListener interface. It is
normally more convenient to extend this class than to implement WindowListener
directly. Notice that none of the WindowConstants close operations actually
terminate program execution. This can be accomplished by extending
WindowAdapter and overriding the methods we are interested in handling (in this
case just the windowClosed() method). We can create an instance of this extended
class, cast it to a WindowListener object, and register this listener with the JFrame
using the addWindowListener() method. This can easily be added to any application
as follows:
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
myJFrame.addWindowListener(l);
The best method of all is to combine WindowAdapter and values from the
WindowConstants interface to present the user with an exit confirmation dialog as
follows:
myJFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
Note: This can also be done for JDialog. However, to do the same thing for a
JInternalFrame we must build a custom JInternalFrame subclass and implement
the PropertyChangeListener interface.
Inserting this code into your application will always display the dialog shown in
figure 3.4 when the JFrame close button is pressed. Note that this functionality is
not used until later chapters in which we work with applications where closing may
cause a loss of unsaved material.
When setting the location of the JFrame, the upper left hand corner of the frame is
the relevant coordinate. So to center a JFrame on the screen we need to subtract
half its width and half its height from the center-of-screen coordinate:
myJFrame.setLocation(dim.width/2 - myJFrame.getWidth()/2,
dim.height/2 - myJFrame.getHeight()/2);
JApplet
class javax.swing.JApplet
JApplet is the Swing equivalent of the AWT Applet class. Like JFrame, JApplet’s
main child component is a JRootPane and its structure is the same. JApplet acts
just like Applet and we will not go into detail about how applets work.
JWindow
class javax.swing.JWindow
JWindow is very similar to JFrame except that it has no title bar, and is not
resizable, minimizable, maximizable, or closable. Thus it cannot be dragged without
writing custom code to do so (e.g. JToolBar’s UI delegate provides this functionality
for docking and undocking). We normally use JWindow to display a temporary
message or splash screen logo. Since JWindow is a RootPaneContainer, we can
treat it just like JFrame or JApplet when manipulating its contents.
Content pane: The content pane is associated with frame. The content pane is the
container that contains the components which resides in the frame. Components
should be added to a frame through content pane and not directly to the frame
itself. getContentPane( ) method of JFrame returns an object of Container class as
follows :
Container c = getContentPane( ) ;
JList:
A list displays a series of items from which the user may select one or more items.
Lists are created with class JList, which inherits from class JComponent. Class
JList supports both single-selection lists (i.e., lists that allows only one item to be
selected at a time) and multiple-selection lists(lists that allow any number of items
to be selected
Single-selection Lists:
In Single-selection list, we can select one item only. The difference with combobox
is that the list displays scrollbars.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class jlist extends JFrame implements ListSelectionListener
{
JList co;
Container c;
public jlist()
{
c=getContentPane();
c.setLayout(new FlowLayout());
Multiple-Selection List:
A multiple-selection list enables the user to select many items from a Jlist. A
SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items
in the list by clicking the first item while holding shift key, then clicking the last
item to select in the range (while holding shift key). A
MULTIPLE_INTERVAL_SELECTION list allows continuous range selection described
for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be
selected by holding the Ctrl key while clicking each item to select. To deselect an
item, hold the Ctrl key while clicking the item a second time.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class jmlist extends JFrame implements ListSelectionListener
{
JList p;
public jmlist()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
String names[]={"Banglore","Hyderabad","Ooty","Chennai","Mumbai",
"Delhi","Kochi","Darjeeling"};
p=new JList(names);
p.setVisibleRowCount(5);
p.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
c.add(new JScrollPane(p));
p.addListSelectionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JTextArea:-
The limitation of JTextField is that we can enter or display the text in one line only.
The limitation is overcome with JtextArea. In JtextArea, we can enter or display and
number of lines of text. We can make a text area not to be used by the user by
using setEditable(false) method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class jtextarea extends JFrame implements ActionListener
{
JButton b1;
JTextArea tf;
JSlider:
JSlider enable the user to select from a range of integer values. Class JSlider
inherits from JComponent. The following figure creates a horizontal JSlider with
tick marks and the thumb that allows the user to select a value.
JMenu:
Steps in total menu creation:
1. create a menu bar (e.g JmenuBar mb=new JmenuBar())
2. add menu bar to the frame (e.g. setJMenuBar(mb))
3. create menus (e.g. Jmenu file=new Jmenu(“File”))
4. add items to each menu (e.g file.add(new JmenuItem(“Open”))
5. add each menu to menu (e.g mb.add(file))
6. add the menubar to the frame (e.g. setJMenuBar(mb))
The character “-“ separates menu items. You may also use the addSeparator()
method to separate menu items.
f1.addSeparator( )
JPopupMenus:
Many computer applications provide so-called context-sensitive popup menus. In
Swing, such menus are created with class JPopupMenu (a subclass of
JComponent). These menus provide options that are specific to the component for
which the popup trigger event was generated. On most systems, the popup trigger
event occurs when the user presses and releases the right mouse button. A popup
menu appears anywhere on the screen when a right mouse button is clicked. A
popup menu appears anywhere on the screen when a right mouse button is clicked.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class PopupMenuDemo extends JApplet
{
private JPopupMenu popup = new JPopupMenu( ) ;
public void init( )
{
Container cp = getContentPane( ) ;
popup.add( new JMenuItem( "undo" ) ) ;
popup.add( new JMenuItem( "redo" ) ) ;
popup.addSeparator( ) ;
popup.add( new JMenuItem( "cut" ) ) ;
popup.add( new JMenuItem( "copy" ) ) ;
popup.add( new JMenuItem( "paste" ) ) ;
cp.addMouseListener( new MouseAdapter( )
{
public void mouseReleased(MouseEvent e )
JTabbedPane:
Tabbed pane is a common user interface component that provide an easy access to
more than one panel( like cardlayout manager ). Each tab is associated with a
single component that will be displayed when the tab is selected.
In the following program, three tabs are added to the tabbed pane. 3 classes are
made for each tab.
import java.awt.*;
import javax.swing.*;
public class TabbedPaneDemo extends JApplet
{
public void init( )
{
JTabbedPane jt = new JTabbedPane( ) ;
jt.add( "Colors", new CPanel( ) ) ;
jt.add( "Fruits", new FPanel( ) ) ;
jt.add( "Vitamins", new VPanel( ) ) ;
getContentPane( ).add( jt );
}
}
class CPanel extends JPanel
{
public CPanel( )
{
JCheckBox cb1 = new JCheckBox( "Red" ) ;
JCheckBox cb2 = new JCheckBox( "Green" ) ;
JCheckBox cb3 = new JCheckBox( "Blue" ) ;
add(cb1) ; add(cb2) ; add(cb3) ;
}
}
class FPanel extends JPanel
{
public FPanel( )
{
JComboBox cb = new JComboBox( ) ;
cb.addItem( "Apple" ) ;
JScrollPane:
JScrollPane scrolls to view its contents. Scrollbars are used to scroll the view
horizontally and vertically.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ScrollPaneDemo extends JApplet
{
public void init( )
{
Container cp = getContentPane();
cp.setLayout( new BorderLayout( ) ) ;
JPanel jp = new JPanel( ) ;
jp.setLayout( new GridLayout( 20, 20 ) ) ;
for( int i = 0 ; i < 20 ; i + + )
for( int j = 0 ; j < 20 ; j + + )
jp.add( new JButton( "Button " + j ) ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ;
JColorChooser:
JColorChooser class provides a pane of controls designed to allow a user to
manipulate and select a color.
import javax.swing. * ;
import java.awt. * ;
import java.awt.event. * ;
public class ColorChooser extends JFrame
{
public ColorChooser( )
{
setTitle("Jcolorchooser Example");
JColorChooser jcc = new JColorChooser( ) ;
JPanel content = ( JPanel ) getContentPane();
content.setLayout(new BorderLayout());
content.add( jcc, "Center" ) ;
addWindowListener( new WindowAdapter( )
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 ) ;
}});
}
public static void main( String args[] )
{
JFrame jf = new JFrame( "Choose the Best Shade" ) ;
ColorChooser cc = new ColorChooser( ) ;
cc.setVisible(true);
}
}
JTrees
Tree is a swing component that can be used to display a hierarchy of data like
Window Explorer.
DefaultMutableTreeNode class is used to create a node.
TreePath getPathForLocation( int x, int y ) returns the path of the node
clicked.
import java.awt.*;
import java.awt.event.* ;
import javax.swing.* ;
import java.util.* ;
import javax.swing.tree.* ; // for DefaultMutableTreeNode and JTree
// import java.applet.* ; not required as Japplet extends Applet
public class JTreeDemo extends JApplet
{
JTree jt ; JTextField jtf ;
public void init( )
{
Container c = getContentPane( ) ;
c.setLayout( new BorderLayout( ) ) ;
// this is the root node and top in the hierarchy
DefaultMutableTreeNode rootnode = new DefaultMutableTreeNode(" Sports ") ;
DefaultMutableTreeNode anode = new DefaultMutableTreeNode( " Air games " ) ;
rootnode.add( anode ) ; // becomes a file to rootnode
// create ogames node add to the rootnode(becomes child node of rootnode )
DefaultMutableTreeNode ogames = new DefaultMutableTreeNode( " OutDoor
Games ") ;
DefaultMutableTreeNode bnode = new DefaultMutableTreeNode( " Basket ball " ) ;
DefaultMutableTreeNode vnode = new DefaultMutableTreeNode( " Volley ball " ) ;
ogames.add( bnode ) ; // becomes file to ogames
ogames.add( vnode ) ; // becomes file to ogames
rootnode.add( ogames ) ; // add ogames to rootnode
// create igames node add to the rootnode(becomes child node of rootnode )
JTables
Table displays data in horizontal and vertical columns. A table can be resized or
moved. We create a table and add it to a scroll pane. Scroll pane is added to the
container.
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class JTableDemo extends JApplet
{
public void init( )
{
Container c = getContentPane( ) ;
c.setLayout( new BorderLayout( ) ) ;
String fields [ ] = { " empid ", " empname ", " empsal " } ;
Object details [ ] [ ] = { { " 1 " , " S N Rao " , " 4500.50 " } ,
{ " 2 " , " S umathi " , " 4567.50 " } ,
{ " 3 " , " Sridhar " , " 2246.30 " } ,
{ " 4 " , " Jyothi " , " 3245.75 " } ,
{ " 5 " , " Jyostna " , " 2500.25 " } } ;
JTable jt = new JTable( details , fields ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ; // if the
rows are more than
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ; //
height of the applet,
JScrollPane jsp = new JScrollPane( jt , v , h ) ; // scroll bar is added
c.add( jsp , " Center " ) ;
}
}