JavaProgramming Unit-IV
JavaProgramming Unit-IV
Chapter – I
AWT Hierarchy
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Component
The class Component is the abstract base class for the non menu user-interface controls of AWT.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the
component.
To create simple awt window example, you need a frame. There are two ways to create a
frame in AWT.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();}}
OUTPUT:
Graphics class:
The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto
Components.
Graphics object is passed as a parameter to paint( ) method of an applet
Graphics class methods to draw on an Applet
g.drawLine(35, 45, 75, 95);
drawLine(int x1, int y1, int x2, int y2)
Line
Used to draw a straight line from point (x1,y1) to (x2,y2).
g.drawRect(35, 45, 25, 35);
Rectangle drawRect(int x, int y, int width, int length)
Used to draw a rectangle with the upper left corner at (x,y) and
with the specified width and length.
g.drawRoundRect(35,45,25,35,10,10);
drawRoundRect(int x, int y, int width, int
Round Edge length, int arcWidth, int arcHeight)
Rectangle
Used to draw a rounded edged rectangle. The amount of rounding
is controlled by arcWidth and arcHeight.
g.drawOval(25, 35, 25, 35);
g.drawOval(25, 35, 25, 25); → circle
Oval / Circle drawOval(int x, int y, int width, int length)
Used to draw an oval inside an imaginary rectangle whose upper
left corner is at (x,y). To draw a circle keep the width and length
the same.
g.drawArc(35, 45, 75, 95, 0, 90);
drawArc(int x, int y, int width, int length,
int startAngle, int arcAngle)
Chapter – II
AWT Controls
AWT controls are the sub classes of AWT Component
Component
– Button
– Checkbox
– Label
– List
– Choice
– Scrollbar
– TextComponent
– TextArea
– TextField
AWT
Compone Constructors Methods
nt
Button() -- Constructs a Button with no label. String getLabel()
Button
Button(String label)-- Constructs a Button Gets the label of this button.
with the specified label.
void setLabel(String label)
Label Label()
Constructs a new label with the specified string void setText(String text)
of text, left justified.
Sets the text for this label to
Label(String text, int alignment) the specified text.
Creates a new scrolling list initialized to display the Adds the specified item to the the
specified number of rows. scrolling list at the position indicated
by the index.
Creates a new choice menu (Drop Down List). Adds an item to this Choice menu.
int getItemCount()
Scrollbar Scrollbar()
Constructs a new text field. Sets the text that is presented by this
text component to be the specified
TextField(int columns) text.
Constructs a new empty text field with the specified String getText()
number of columns.
Returns the text associated with text
TextField(String text) box
TextArea TextArea()
Constructs a new text area with the empty string as text. int getRows()
Constructs a new text area with the specified text, and Sets the number of rows for this text
with the rows, columns, and scroll bar visibility as area.
specified.
SCROLLBARS_BOTH
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_NONE
SCROLLBARS_VERTICAL_ONLY
Panes
Scrollpane:
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll
pane to display a large component or a component whose size can change dynamically.
Constructors
Constructor Purpose
JScrollPane()
JScrollPane(Component) It creates a scroll pane. The Component parameter, when present, sets
JScrollPane(int, int) the scroll pane's client. The two int parameters, when present, set the
vertical and horizontal scroll bar policies (respectively).
JScrollPane(Component, int,
int)
o The Dialog control represents a top level window with a border and a title used to take some form of input from the
user.
o It inherits the Window class.
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
MenuBar class:
The MenuBar class provides menu bar bound to a frame.
Constructors
MenuBar( ) – default constructor.
In order to associate the menu bar with a Frame object, call the frame's setMenuBar() method.
Example :
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[])
{
new MenuExample(); }}
OUTPUT:
Chapter – III
Event Handling
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are
generated as result of user interaction with the graphical user interface components. For example, clicking on
a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the
page are the activities that causes an event to happen.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an event occurs. Java
Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events..
The Delegation Event Model has the following key participants namely:
Event Source - The source is an object on which event occurs. EX: Button
Event Listener - It is also known as event handler. Listener is responsible for generating response to an
event. listener is an interface which provides set of respective methods called event handlers to handle the
event. Listener waits until it receives an event. Once the event is received , the listener process the event an
then returns.
Ex: ActionListener interface which contains actionPerformed( ) method to handle button event
Event Object - which describes the event
When ever an event occurs it is delegated or notified to respective registered event listener and the listener invokes
respective event handler to process that event thus it is called as Delegation event model
The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event.
To add/register event listener
To get event notifications The event sources must be registered with Event Listeners using the following method
public void addTypeListener(TypeListener object)
ex: b.removeActionListener(this)
ActionEvent ActionListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
All the interfaces and the methods in them.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
The following program changes the applet background color, whenever the mouse event occurs.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
this.addMouseListener(this);
}
setBackground(Color.blue);
}
setBackground(Color.cyan);
}
setBackground(Color.green);
}
setBackground(Color.magenta);
}
setBackground(Color.yellow);
}
}
public void keyTyped(KeyEvent k)
{
msg=”KEY TYPED”;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
import java.awt.event.*;
Button b;
TextField tf;
tf=new TextField();
//register listener
b.addActionListener(this);
add(b);
add(tf);
tf.setText("Welcome");
}}
Adapter Classes
• Java adapter classes provide the default implementation of listener interfaces.
• If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces.
MouseAdapter Example
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{
Frame f;
MouseAdapterExample( ){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
} public static void main(String[] args) {
new MouseAdapterExample(); }}
Output:
KeyAdapter Example
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()); }
} public static void main(String[] args) {
new KeyAdapterExample(); }}
Output: