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

JavaProgramming Unit-IV

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, hierarchy, and methods for creating graphical user interfaces. It covers various AWT controls like buttons, checkboxes, and text fields, as well as event handling mechanisms using the Delegation Event Model. Additionally, it includes examples of creating windows, dialogs, menus, and handling user interactions through events.

Uploaded by

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

JavaProgramming Unit-IV

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, hierarchy, and methods for creating graphical user interfaces. It covers various AWT controls like buttons, checkboxes, and text fields, as well as event handling mechanisms using the Delegation Event Model. Additionally, it includes examples of creating windows, dialogs, menus, and handling user interactions through events.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT –IV

Chapter – I

AWT (Abstract Windowing Tool Kit)

 Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
 The java.awt package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

AWT Hierarchy

The hierarchy of Java AWT classes are given below.

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.

Component represents an object with graphical representation.

Constructor - protected Component()

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the
component.

public void setLayout(LayoutManager m) defines the layout manager for the


component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.

To create simple awt window example, you need a frame. There are two ways to create a
frame in AWT.

By extending Frame class (inheritance)

By creating the object of Frame class

Example : Extending Frame class

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)

Used to draw an arc inside an imaginary rectangle whose upper


Arc left corner is at (x,y). The arc is drawn from the startAngle to
startAngle + arcAngle and is measured in degrees.
A startAngle of 0ºpoints horizontally to the right (like the unit
circle in math). Positive is a counterclockwise rotation starting at
0º.
int [ ] x = {20, 35, 50, 65, 80, 95};
int [ ] y = {60, 105, 105, 110, 95, 95};
g.drawPolygon(x, y, 6);
drawPolygon(int x[ ], int y[ ], int n)
Polygon
Used to draw a polygon created by n line segments. The
command will close the polygon. (x-coordinates go in one array
with accompanying y-coordinates in the other)
g.drawString("Java is cool!", 40, 70);
String drawString(String str, int x, int y); --Draws a string starting at the
(text) point indicated by (x,y). Be sure you leave enough room from the
top of the screen for the size of the font.

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)

Sets the button's label to be


the specified string.

Checkbox Checkbox( ) -- Creates a check box without any label Checkbox


getSelectedCheckbox()
Checkbox(String label)
Gets the current choice from
-- --Creates a check box with the specified label. this check box group.

Checkbox(String label, boolean state) void setSelectedCheckbox(Checkbox


box)
--Creates a check box with the specified label and
sets the specified state. Sets the currently selected check
box in this group to be the
Checkbox(String label, boolean state, specified check box.
CheckboxGroup group)

--Constructs a Checkbox with the specified label,


set to the specified state, and in the specified
check box group.

Note : If we use CheckboxGroup it creates


Radio Buttons .

Label Label()

Constructs an empty label. String getText( )

Label(String text) Gets the text of this 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.

Constructs a new label that presents the specified


string of text with the specified alignment.
Alignment can be
 Label.CENTER -- Indicates that the label should
be centered.
 Label.LEFT -- Indicates that the label should be
left justified.
 Label.RIGHT -- Indicates that the label should
be right justified.
List List()

Creates a new scrolling list. void add(String item)

List(int rows) Adds the specified item to the end of


scrolling list.
Creates a new scrolling list initialized with the specified
number of visible lines.

List(int rows, boolean multipleMode) void add(String item, int index)

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.

Choice Choice() void add(String item)

Creates a new choice menu (Drop Down List). Adds an item to this Choice menu.

int getItemCount()

Returns the number of items in this


Choice menu.

Scrollbar Scrollbar()

Creates horizontal and vertical scrollbar.


TextField TextField() void setText(String t)

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

Constructs a new text field initialized with the specified


text.
TextField(String text, int columns)

Constructs a new text field initialized with the specified


text to be displayed, and wide enough to hold the specified
number of columns.

TextArea TextArea()

Constructs a new text area with the empty string as text. int getRows()

TextArea(int rows, int columns) Returns the number of rows in the


text area.
Constructs a new text area with the specified number of
rows and columns and the empty string as text. int getColumns()

TextArea(String text) Returns the number of columns in this


text area.
Constructs a new text area with the specified text.
void insert(String str, int pos)
TextArea(String text, int rows, int columns)
Inserts the specified text at the
Constructs a new text area with the specified text, and specified position in this text area.
with the specified number of rows and columns
void setColumns(int columns)
Note:TextField contains single line and TextArea contains
multiple lines of data Sets the number of columns for this
text area.
TextArea(String text, int rows, int columns, int
scrollbars) void setRows(int rows)

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.

Scroll Bars can be

 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)

Dialog – Creates a child window on a parent window

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.

Unlike Frame, it doesn't have maximize and minimize buttons.

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);
}

public static void main(String args[])


{
new DialogExample();
}}
Output:

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.

MenuItem &Menu class:

 MenuItem class adds a simple labeled menu item on menu.


 The items used in a menu must belong to the MenuItem or any of its subclass.
 Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem
class

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: To register Button events


public void addActionListener(ActionListener a){}
Button b=new Button();
b.addActionListener(this);

To remove event listener we use

public void removeTypeListener(Typeistener listener)

ex: b.removeActionListener(this)

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
All the interfaces and the methods in them.

Event Generated by Listener Interface Methods in them


Action event Pressing a button ActionListener actionPerformed()
Adjustment event Scroll bar is AdjustmentListener adjustmentValueChanged()
manipulated
Component event A component is ComponentListener componentHidden()
hidden, moved, componentMoved()
resized, or shown componentResized()
componentShown()
Container event A component is added ContainerListener componentAdded()
or removed from a componentRemoved()
container
Focus event A component gains or FocusListener focusGained()
loses focus focusLost()
Item event An item is selected or ItemListener itemStateChanged()
deselected
Key event A key is pressed, KeyListener keyPressed()
released or typed keyReleased()
keyTyped()
Mouse event Mouse button is MouseListener mouseClicked()
clicked, pressed or mouseEntered()
released. Mouse mouseExited()
pointer enters leaves a mousePressed()
component mouseReleased()
Mouse event Mouse pointer is MouseMotionListen mouseDragged()
dragged or moved er mouseMoved()
Text event Text value is changed TextListener textValueChanged()
Window event A window is WindowListener windowActivated()
activated, closed, windowClosed()
deactivated, windowClosing()
deiconfied, opened, or windowDeactivated()
quit windowDeiconified()
windowIconified()
windowOpened()

Programs to demonstrate Mouse Events


Program 1:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MouseEvents extends Applet implements MouseListener,MouseMotionListener


{
String msg=” “;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
public void mousePressed(MouseEvent me)
{
msg=” mouse pressed”;
repaint();
}
public void mouseClicked(MouseEvent me)
{
msg=” mouse clicked”;
repaint();
}
public void mouseEntered(MouseEvent me)
{
msg=” mouse entered”;
repaint();
}
public void mouseExited(MouseEvent me)
{
msg=” mouse exited”;
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg=” mouse released”;
repaint();
}
public void mouseMoved(MouseEvent me)
{
msg=” mouse moved”;
repaint();
}
public void mouseDropped(MouseEvent me)
{
msg=” mouse dropped”;
repaint();
}
public void mouseDragged(MouseEvent me)
{
msg=” mouse dragged”;
repaint();
}}
Program 2:

The following program changes the applet background color, whenever the mouse event occurs.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseEvent1 extends Applet implements MouseListener{

public void init() {

this.addMouseListener(this);
}

public void mouseClicked(MouseEvent e){

setBackground(Color.blue);
}

public void mouseEntered(MouseEvent e){

setBackground(Color.cyan);
}

public void mouseExited(MouseEvent e){

setBackground(Color.green);
}

public void mousePressed(MouseEvent e){

setBackground(Color.magenta);
}

public void mouseReleased(MouseEvent e){

setBackground(Color.yellow);
}

Programs to demonstrate Key Events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
msg=”KEY PRESSED”;
repaint();
}
public void keyReleased(KeyEvent k)
{
msg=” KEY RELEASED”;
repaint();

}
public void keyTyped(KeyEvent k)
{
msg=”KEY TYPED”;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

Output:

Programs to demonstrate Button Events


import java.awt.*;

import java.awt.event.*;

class ButtonEvent extends Applet implements ActionListener

Button b;
TextField tf;

public void init()

b=new Button(“click me”);

tf=new TextField();

//register listener

b.addActionListener(this);

add(b);

add(tf);

public void actionPerformed(ActionEvent e)

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.

• The adapter classes are found in java.awt.event,


java.awt.event Adapter classes

Adapter Class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener

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:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy