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

Unit -5 - OOPS through Java

Uploaded by

Srivamsi
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)
7 views

Unit -5 - OOPS through Java

Uploaded by

Srivamsi
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/ 53

Dr. P.M.Manohar, Dept.

of CSE, Raghu Engineering College(A), Visakhapatnam OOPS


through
Java –
Unit 5

Course Objectives of this Unit:

 Emphasize the concepts of AWT

Course Outcomes at the end of this Unit:


 Develop GUI applications using AWT

Syllabus
Event handling: event delegation model, sources of event, Event Listeners,
adapter classes, inner classes. AWT: introduction, components and containers,
Button, Label, Checkbox, Radio Buttons, List Boxes, Choice Boxes, Container
class, Layouts, Menu and Scrollbar.

Event handling: Introduction

• An object resides in a particular state until it is made to transit to other state.


• This transition occurs due to an event.
• For example, we want an object to invoke a function when an action is generated, e.g.
– pressing a key on the keyboard,
– moving the mouse,
– clicking on a button, etc.
• The object which generates the event, i.e. the source of the event is known as the event
generator.
• The object, responsible for performing the task when an event occurs is called the event
handler.
– There may be more than one event handlers for one single event generated.
• How do these handlers know that a particular event has occurred so that they can perform
their activity?
• There is a registration process, undertaken by the event object, for each of its event
handlers.
• This registration involves the event handler simply asking the event generator to inform
about the occurrence of an event.
• By registering, the event generator is able to keep track of all the registered event
handlers.

1
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Event Delegation Model


• In Event Delegation Model, a source generates events which are sent to one or more
listeners.
• The listeners receive the event, and process them.
• The processing logic applied for handling an event is totally segregated by the logic that
generates the event, i.e. the event-generating component can be designed differently
than the event-processing component.
• Actually the event generating component delegates the responsibility of performing an
event-based action to a separate event-performing component.
The model has three dimensions, namely events, event sources and event listeners.

• An event is an object that describes a state change in the source.


• It may be generated directly because of interaction with the components of GUI
environment or any other reason such as expiry of timer, completion of an operation, etc.
• An event source is an object which generates the event. Generation of event must cause a
change in the state of the source. A source can generate more than one event.
• Event Listeners are the objects that get notified when an event occurs on an event source.

java.awt.AWTEvent
• The java.awt.AWTEvent class is the root class for all AWT Events.
• java.awt.event packages includes the definition of events classes, listeners interfaces, and
adapters classes, which from the basics for event handling.
Event classes
• Java has a predefined hierarchy of event-related classes, at the root of which is
EventObject.
• It is actually a member of java.util package. This class has constructors and methods
defined as its members.
• One such constructor is EventObject(Object src_obj)
– where, src_obj is the object, which generates the event.
• EventObject has methods like getSource() and toString().
– getSource() – returns the source of the event
– toString() – returns the string equivalent of the event

2
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

ActionEvent

• This event is generated by a component (such as a Button) when the component-specific


action occurs (such as click).

• The event is passed to an ActionListener object which is registered to receive the event
notification using the component’s addActionListener method.

• The object that inherits the ActionListener interface is passed to the ActionEvent when an
event occurs. Some of the fields, constructors, and methods associated with the
ActionEvent class

Field Summary of ActionEvent

3
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Constructor of ActionEvent

Methods of ActionEvent

AdjustmentEvent

• The adjustment events are generated by Adjustable objects like scroll bar.

Fields of Adjustment Event

4
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Constructor of AdjustmentEvent

Methods of AdjustmentEvent

KeyEvent

• KeyEvent is an event which indicates that a keystroke occurred in a component.

– public class KeyEvent extends InputEvent

• is generated by component object (such as a text field, Applet, Frame) when a key is
pressed, released, or typed.

• The event is passed to a KeyListener object which is registered to receive the event
notification using the component’s addKeyListener method.

• There can be three types of key events, which are identified by integer constants.

– KEY_PRESSED (it is generated when any key is pressed)

– KEY_TYPED (it is generated if a valid Unicode character could be generated)

– KEY_RELEASED (it is generated when any key is released)

5
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Few Integers constants in KeyEvent

Constructor

Methods in KeyEvent

6
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

MouseEvent

• It is an event which indicates that a mouse action occurred in a component.

• A mouse action occurs in a particular component if and only if the mouse cursor is over the
defined part of the component’s bounds when the action happens.

– public class MouseEvent extends InputEvent

• There are eight types of mouse events defined in the MouseEvent class.

• The MouseEvent class defines them as integer constants to identify each of these events.

Fields of MouseEvent

Constructors of MouseEvent

7
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Methods of MouseEvent

FocusEvent

• This event is generated when a component gains or loses focus.

• There are two types of focus events: permanent and temporary.

– Permanent focus event occurs when the user explicitly changes focus from one
component to other, e.g. by pressing tab key.

– Temporary focus event occurs when the focus is lost due to operations like Window
deactivated. In this case, when the window will again be activated, the focus will
be on same component.

Fields of FocusEvent

8
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Constructor of FocusEvent

Methods of FocusEvent

ItemEvent

• It is an event which shows whether an item was selected or de-selected.

– public class ItemEvent extends AWTEvent

• This event is generated by an ItemSelectable object (such as a List), where the event is
generated when an item of the list is either selected or de-selected.

• The event generated is passed to every ItemListener object which is registered to receive
such events.

• The method addItemListener() is used for this registration process.

Fields of ItemEvent

9
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

TextEvent

• This event indicates the change in the object’s text.

– public class TextEvent extends AWTEvent

• This event is generated by an object (such as a TextComponent) whenever its text


changes. The event is passed to every TextListener object which is registered to receive
such events.

• The method addTextListener() is used for this registration process.

Source of Events

• Button

• Choice

10
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

• MenuItem

• List

• Checkbox

• Window

• Scrollbar

• Text Components

• Event Listeners are created by implementing one or more interfaces defined by the
java.awt.event package.

• Whenever a source generates an event, it basically invokes the appropriate method


defined in the listener interface.

• The method has a event object passed as an argument to it.

Listeners

KeyListener

• This interface has three methods defined within it.

– void keyPressed(KeyEvent e) – invoked when a key is pressed

– void keyReleased(KeyEvent e) - invoked when a key is released

– void keyTyped(KeyEvent e) - invoked when a character is typed

MouseListener

• The interface has five methods, having the signatures as follows:

– void mouseClicked(MouseEvent e)

11
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

– void mouseEntered(MouseEvent e)

– void mousePressed(MouseEvent e)

– void mouseReleased(MouseEvent e)

– void mouseExited(MouseEvent e)

MouseMotionListener

• The interface has two methods having the signatures,

– void mouseMoved(MouseEvent e)

– void mouseDragged(MouseEvent e)

• mouseMoved() is invoked when the mouse is moved from one place to another and
mouseDragged() is used when the mouse is dragged.

MouseWheelListener & ItemListener

• MouseWheelListener has only one method, having the signature,

– void mouseWheelmoved(MouseEvent e) - invoked when the mouse wheel is moved.

• ItemListener has only one method defined as,

– void itemStateChanged(ItemEvent e) - invoked when the state of the item changes.

ActionListener, TextListener & FocusListener

• ActionListener has only one method

– void actionPerformed(ActionEvent e) - invoked when any action event is


performed.

• TextListener has only one method

– void textChanged(TextEvent e) - invoked whenever there is a change in text field


or text area.

• FocusListener interface has two methods,

– void focusGained(FocusEvent e) - invoked when the component obtains keyboard


focus and focusLost()

12
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

– void focusLost(FocusEvent e) - is invoked when the component looses the keyboard


focus.

WindowListener

• This interface has seven methods

– void windowActivated(WindowEvent e)

– void windowClosed(WindowEvent e)

– void windowClosing(WindowEvent e)

– void windowOpened(WindowEvent e)

– void windowDeactivated(WindowEvent e)

– void windowIconified(WindowEvent e)

– void windowDeiconified(WindowEvent e)

Model

• Each source, generating the events must register event listeners to itself, so that listeners
get the license for receiving the events from the respective source.

• Each type of event has its own registration method, having the form,

– public void addTypeListeners(TypeListener tl)

• These listeners, once registered for events from a particular source, can get unregistered
also using

– public void removeTypeListener(TypeListerner tl)

• Once the listener objects are registered, they must implement the methods to receive and
process the event notifications sent by source.

/*<applet code=”MouseMotionEx.class” width=300 height=300></applet>*/

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

import java.awt.event.*;

public class MouseMotionEx extends Applet implements MouseMotionListener {

int xcord; int ycord;


13
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public void init(){ addMouseMotionListener(this); }

public void paint(Graphics g){

g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,ycord);}

public void mouseMoved(MouseEvent me){

xcord = me.getX();

ycord = me.getY();

repaint();}

public void mouseDragged(MouseEvent me){}}

Another way of doing same

/*<applet code = “MouseMotionEx.class” width = 700 height = 700 > </applet>*/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class MouseMotionEx extends Applet

int xcord; int ycord;

public void init(){

addMouseMotionListener (new Demo(this));}

public void paint (Graphics g){

g.drawString (“(“+x cord +”, “+y cord+”)”);

}}

class Demo implements MouseMotionListener

MouseMotionEx m;

Demo(MouseMotionEx m)
14
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

this.m=m;

public void mouseMoved(MouseEvent me) {

m.xcord = me.getX();

m.ycord = me.getY();

m.repaint();}

public void mouseDragged(MouseEvent me) {}

Adapter classes

• In listener interfaces, you have to implement all the methods defined in that interface

• This can be annoying at times, particularly when you need to implement methods of the
interface, which might not actually be used.

• In order to simplify things, Java came up with the concept of adapter classes.

• JDK defines corresponding adapter classes for listener interfaces containing more than
one methods e.g. for MouseMotionListener, MouseMotionAdapter class has been defined.

• Adapter classes provide empty definitions for all the methods of their corresponding
Listener interface.

• It means that MouseMotionAdapter class inherently implements MouseMotionListener


interface.

15
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

How to use Adapter classes?

/*<applet code=”AdapterDemo.class” width=300 height=300></applet>*/

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

import java.applet.*;

public class AdapterDemo extends Applet {

int xcord,ycord;

public void init(){

addMouseMotionListener(new MouseDemo(this));

public void paint(Graphics g){

g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,ycord);

}}

class MouseDemo extends MouseMotionAdapter

AdapterDemo d;

MouseDemo(AdapterDemo d)

this.d = d;

16
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public void mouseMoved(MouseEvent me){

d.xcord = me.getX();

d.ycord = me.getY();

d.repaint();

}}

Inner classes

• An inner class can be defined and instantiated all inside a class, or even within an
expression.

– member classes,

– local classes, and

– annoymous classes.

• Member classes

– are included in the class definition just like fields and methods.

– can either be static or instance.

– Static member class: A member class can be static with access only to the static
members of the class to which it belongs.

17
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

– Instance member class: A member class can be instance with access to both the
static and instance members of the class that contains it.

• Local classes

– A local class is defined within a code block, typically in a method. An instance of a


local class exists only during the execution of the method

• Anonymous Inner classes

– An anonymous inner class is one that is not assigned a name.

– Such classes are created on the fly i.e. they are created, instantiated, used and
garbage collected when they are done.

– They are automatically assigned a name as Outerclassname$1.

– This anonymity helps in eliminating the unnecessary named objects. Besides, it


makes the program more readable.

Use of Member Inner Class

/*<applet code = OuterClass.class width=600 height=600> </applet>*/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class OuterClass extends Applet {

public void init() {

addKeyListener(new InnerClass()); }

class InnerClass extends KeyAdapter {

public void keyPressed(KeyEvent ke) {

showStatus(“key down”); }

public void keyReleased(KeyEvent ke){

showStatus(“key up”); }}}

Use of Anonymous Inner Class

18
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

/*<applet code=”AnonyKeyListDemo.class” width=300 height=300> </applet>*/

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class AnonyKeyListDemo extends Applet {

public void init(){

addKeyListener(new KeyAdapter(){

public void keyPressed(KeyEvent ke){

showStatus(“Key Pressed”);}

public void keyReleased(KeyEvent me){

showStatus(“Key Released”); }

}); }}

AWT: Introduction

• The Java Foundation Classes (JFC) provide two frameworks for building GUI-based
application and interestingly both rely on the same event handling model:

– AWT

– Swing

19
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

• AWT relies on the underlying operating system on a specific platform to represent its GUI
components (i.e components in AWT are called Heavyweight),

• Swing implements a new set of lightweight GUI components that are written in Java and
has a pluggable look and feel.

• These lightweight components are not dependent on the underlying window system.

Components and Containers

• A graphical user interface is developed with the help of graphical elements like

– buttons, scrollbars, lists, textfields, etc.

• These elements are called components.

• In AWT, these components are instances of the respective Component classes.

• Components cannot exist alone; they are found within containers.

• Actually, containers are themselves components, thus they can be placed inside other
containers.

• In AWT, all containers are objects of class Container or one of its subtypes.

Hierarchy of classes in AWT

20
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Few classes in AWT

21
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Component

• subclass of the Object class & super class of classes such as

– Button,

– Label,

– CheckBox,

– RadioButton, Choice, Canvas, etc

• Componenets are added to a window using the add() method

– Component add(Component ComObj)

– ComObj is the object of the Component, which is to be added

– This method returns the reference to the ComObj.

22
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

• If you wish to remove a Component from a window, use remove() method

– void remove(Component ComObj)2

Components as Event Generator

Components as Event Generator

23
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Button

• The Button class belongs to java.awt package

– public class Button extends Component implements Accessible

• This class creates a button which when pushed or pressed generates an event.

• The two constructors belonging to this Button class are:

– Button() throws HeadlessException

– Button(String str)throws HeadLessException;

• To create a button

– Button buttonName = new Button(Str);

– ‘buttonname’ is the name you give to the button object and ‘Str’ is the text you
want to appear on the button.

• Once the object for Button is created, it needs to be added to the applet or any other
container using

– add(buttonname);

– void setLabel(String str) for changing the button’s label

– String getLabel() for getting the Buttons label’s text

Button Example

red.addActionListener(this);

white.addActionListener(this);

blue.addActionListener(this);}

public void actionPerformed(ActionEvent ae){

String str = ae.getActionCommand();

if (str.equals(“Red”)) {

setBackground(Color.red);}

else if (str.equals(“white”)) {

24
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

setBackground(Color.white);}

else if (str.equals(“blue”)){

setBackground(Color.blue);}

repaint();}}

Label

• Labels consist of a text string for display only and they never call an action method.
25
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

• A Label can be justified LEFT, RIGHT, or CENTERED.

– new Label(“This label is for demonstration.”, Label.RIGHT);

Label Example

/*<applet code=”LabelClass” width=350 height=100></applet>*/

import java.applet.*;

import java.awt.*;

public class LabelClass extends Applet {

public void init(){

Label firstLabel = new Label(“Labels exist simply “);

add(firstLabel);

Label secLabel = new Label(“to place text on the screen”);

add(secLabel);

Label thirdLabel = new Label(“They can be aligned left, right or center.”);

add(thirdLabel);}}

26
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Checkbox

• Checkboxes are used as on-off or yes-no switches

• if you click on an unchecked checkbox, it will get checked and vice versa.

• Constructors of Checkbox

– Checkbox()

– Checkbox(String str)

– Checkbox(String str, boolean on)

– Checkbox(String str, CheckBoxGroup cbg, boolean on)

Methods of Checkbox class

27
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Checkbox Example

/*<applet code=CheckboxClass.class width=400 height=100></applet>*/

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CheckboxClass extends Applet implements ActionListener {

Button submit;

Checkbox name1;

Checkbox name2;

Checkbox name3;

public void init(){

name1 = new Checkbox (“Ram”,null,false);

name2 = new Checkbox (“Ramesh”,null,false);

name3 = new Checkbox (“Naresh”,null,false);

Font f = new Font (“Arial”,Font.ITALIC,14);

submit = new Button(“SUBMIT”);

add(name1); add(name2); add(name3); add(submit);

submit.addActionListener(this); }

public void actionPerformed(ActionEvent ae) {

String str = ae.getActionCommand();

if (str.equals(“SUBMIT”)) repaint();}

public void paint (Graphics g) {

g.setFont(f);

g.setColor(Color.blue);

if (name1.getState())
28
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

g.drawString(“Ram”,50,60);

if (name2.getState())

g.drawString(“Ramesh”,50,80);

if (name3.getState())

g.drawString(“Naresh”,50,100); }}

Radio Buttons

• are special kind of checkboxes where only one box can be selected at a time.

• The CheckboxGroup class is used to group together a set of checkboxes

– CheckboxGroup fruits = new CheckboxGroup();

• After creating checkbox group, the individual checkboxes are added to that group.

– add(new Checkbox(“mango”, fruits, false));

– add(new Checkbox(“papaya”, fruits, false));

– add(new Checkbox(“guava”, fruits, false));

– add(new Checkbox(“apple”, true, yes));

Radio Button Example

/*<applet code=”RadioDemo.class” width=300 height=200></applet>*/

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

import java.awt.event.*;

29
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public class RadioDemo extends Applet implements ItemListener{

Checkbox red, white, green; CheckboxGroup cbg;

public void init(){

add(new Label(“The 4 radio buttons will change the screen color.”));

cbg = new CheckboxGroup();

red = new Checkbox(“Red”,cbg,false);

white = new Checkbox(“White”,cbg,false);

green = new Checkbox(“Green”,cbg,false);

add(new Label(“Notice that you can only select one radio button.”));

add(new Label(“And selecting a radio button triggers an event”));

add(new Label(“that we use to change the screen color.”));

add(red);

add(white); add(green);

red.addItemListener(this);

white.addItemListener(this);

green.addItemListener(this); }

public void itemStateChanged(ItemEvent ie){

String str = (String) ie.getItem();

if (str.equals(“Red”)) {

setBackground(Color.red);}

else if (str.equals(“White”)) {

setBackground(Color.white);}

else if (str.equals(“Green”)){

setBackground(Color.green);}

repaint();}}
30
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

List

• provides a multiple choice, scrolling list of values that may be selected alone or together

• List class has the following constructors:

– List()

– List (int no_of_rows)

– List(int no_of_rows, boolean multi_select)

• To create a List and add items to it

– List anyList = new List(10, true);

31
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

– anyList.add(“apple”);

– anyList.add(“mango”);

– anyList.add(“guava”);

– thelist.add(“Coffee”, 0); // adds at the first position

Few Methods of List class

Example

/*<applet code=ShopList.class width=600 height=600></applet>*/

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

public class ShopList extends Applet implements ActionListener {

List original; List copy;

public void init(){

original= new List(8,false);

copy= new List(10,false);

populateList();

32
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

add(original);

Button b1 = new Button(“>>>>”);

add(b1); add(copy);

Button b2 = new Button(“Clear”);

add(b2);

add(new Label(“Select an item from the list on the left and hit >>>> to place it in the
other list”));

b1.addActionListener(this); b2.addActionListener(this);}

public void populateList(){

original.add(“Grocery”);

original.add(“Fruits”);

original.add (“Ice-cream”);

original.add(“Vegetables”);

original.add(“Garments”);

original.add(“Baby Food”);}

public void actionPerformed(ActionEvent ae){

String str = ae.getActionCommand();

if (str.equals(“>>>>”) && original.getSelectedIndex ()>=0) {

copy.add(original.getSelectedItem());

original.remove(original.getSelectedIndex());}

else if(str.equals(“Clear”)) {

original.removeAll();

copy.removeAll();

populateList(); }

repaint(); }}

33
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Choice box

• provides a pop-up menu of text string choices

• current choice is displayed on top.

– Choice c = new Choice();

• the add method enables you to add new entries.

– c.add(“Red”);

– c.add(“Green”);

• The currently selected item can be changed by using select() method.

• The selection can be made based on name or index. For e.g.

– c.select(“Red”);

– c.select(0);

– getSelectedIndex() - return the position of the selected item

– getSelectedItem() - returns the name of the selected item

• The Listener for handling Choice change events is ItemListener.

TextField and TextArea

• The TextField class handles single line of text.

• The TextArea is used for handling multiple lines of text.

34
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Methods of TextField

TextArea

35
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Few methods of TextArea

Container classes

• Window

– Window is a top-level display surface. An object of Window class is not Attached


to nor embedded within another container. An instance of the Window does not
have border, title bar or menu.

• Frame

– Frame is a top-level window with a border and title. An instance of the Frame class
may have a menu bar, title bar and borders. It is otherwise like an object of the
Window class.

• Dialog

– Dialog is top-level display surface (a window) with a border and title. An object of
the Dialog class cannot exist without an associated object of the Frame class.

• Panel

– Panel is generic container for holding components. An instance of the Panel class
provides a container to which components can be added. It does not add any new
method; it simply implements the Container.

36
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Layouts

• FlowLayout

• BorderLayout

• GridLayout

• GridbagLayout

FlowLayout

• arranges components from left-to-right and top-to-bottom, centering components


horizontally.

• The direction of flow is determined by the container’s componentOrientation property.

– ComponentOrientation.LEFT_TO_RIGHT : Items run left to right and lines flow top


to bottom, e.g. English, French, etc.

– ComponentOrientation.RIGHT_TO_LEFT : Items run right to left and lines flow top


to bottom, e.g. Arabic, Hebrew, etc.

• There is five pixel gap between the components arranged in this layout.

• the default layout for the Applet.

Fields of FlowLayout

37
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Constructors of FlowLayout

Example

/*<applet code=FlowLayoutDemo.class width=600 height=350></applet>*/

import java.applet.Applet; import java.awt.*;

public class FlowLayoutDemo extends Applet{

LayoutManager flowLayout;

Button [] Buttons;

public FlowLayoutDemo() {

int i;

flowLayout = new FlowLayout ();

setLayout (flowLayout);

Buttons = new Button [6];

for (i = 0; i < 6; i++) {

Buttons[i] = new Button ();

Buttons[i].setLabel (“Button “ + (i + 1));

add (Buttons[i]);}}}

38
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Output

BorderLayout

• This is the default layout of the Frame.

– public class BorderLayout extends Object implements LayoutManager2,


Serializable

• There can be only one component in each region and the regions are identified as
constants:

– NORTH, SOUTH, EAST, WEST, and CENTER.

• Any of these five constant names can be used while adding a component to a container.

– Panel pnl = new Panel();

– pnl.setLayout(new BorderLayout());

– pnl.add(new Button(“submit”), BorderLayout.NORTH);

39
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Fields of BorderLayout

Example

import java.awt.*;

public class BLayoutDemo extends Frame {

public BLayoutDemo(String title) {

super(title);

add(new Button(“North”),BorderLayout.NORTH);

add(new Button(“South”),BorderLayout.SOUTH);

add(new Button(“East”),BorderLayout.EAST);

add(new Button(“West”),BorderLayout.WEST);

add(new Button(“Center”),BorderLayout.CENTER);

setSize(400, 270);

setVisible(true);}

40
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public static void main(String[] args) {

BLayoutDemo blaypout = new BLayoutDemo(“Border Layout Example”);}}

Output

CardLayout

• Each component is treated as a card by cardLayout object.

• Each card kept on another like a stack and only one card can be visible at a time.

• When the container is displayed after adding the first component, then the first component
is visible.

• The ordering of cards is determined by the container’s own internal ordering of its
component objects.

• CardLayout defines a set of methods that allow an application to flip through these cards
sequentially, or to show a specified card.

Example

import java.awt.*;

import java.awt.event.*;

public class CardDemo extends Frame implements ActionListener {

Panel cardPanel; Panel p1, p2, p3; Panel buttonP;

41
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Button B1,B2,B3; CardLayout cLayout;

public void cardDemo(){

cardPanel = new Panel();

cLayout = new CardLayout();

cardPanel.setLayout(cLayout);

p1 = new Panel();

p1.setBackground(Color.red);

p2 = new Panel();

p2.setBackground(Color.yellow);

p3 = new Panel();

p3.setBackground(Color.green);

B1 = new Button(“Red”);

B1.addActionListener(this);

B2 = new Button(“Yellow”);

B2.addActionListener(this);

B3 = new Button(“Green”);

B3.addActionListener(this);

buttonP = new Panel();

buttonP.add(B1);

buttonP.add(B2);

buttonP.add(B3);

cardPanel.add(p1, “B1”);

cardPanel.add(p2, “B2”);

cardPanel.add(p3, “B3”);

setLayout(new BorderLayout());
42
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

add(buttonP, BorderLayout.SOUTH);

add(cardPanel, BorderLayout.CENTER);

setVisible(true); setSize(300,200);

setTitle(“DemoCard”);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){

System.exit(0);}});}

public void actionPerformed(ActionEvent e){

if (e.getSource() == B1)

cLayout.show(cardPanel, “B1”);

if (e.getSource() == B2)

cLayout.show(cardPanel, “B2”);

if (e.getSource() == B3)

cLayout.show(cardPanel, “B3”);}

public static void main(String a[]){

CardDemo demo=new CardDemo();

demo.cardDemo();} }

GridLayout

• public class GridLayout extends Object implements LayoutManager, Serializable

• lays out a container’s components in a rectangular grid.

Example

import java.awt.event.*;

import java.awt.*;

class GridLayoutDemo extends Frame{

43
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public GridLayoutDemo() {

super(“Laying Out Components using GridLayout”);

Panel p = new Panel(new GridLayout(5,2, 20,50));

p.add(new Label(“Name”));

p.add(new TextField(5));

p.add(new Label(“Roll No”));

p.add(new TextField(3));

p.add(new Label(“Class”));

p.add(new TextField(3));

p.add(new Label(“Total Marks”));

p.add(new TextField(3));

p.add(new Button(“Submit”));

p.add(new Button(“Cancel”));

add(p);

setSize(400,400);

setVisible(true);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);}});}

public static void main(String[] args) {

GridLayoutDemo g=new GridLayoutDemo();

}}

Output

44
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

GridBagLayout

• We can arrange components in horizontal as well in vertical direction or by positioning


them within a cell of a grid

• components need not be of same size in a row.

• each row can contain dissimilar number of columns.

• GridBagConstraint contains the constraint which includes the

• height, width of a cell, placement and alignment of components.

• GridBagLayout object maintains a rectangular grid of cell.

• Component can occupy one or more cells, a.k.a its display area.

• ComponentOrientation class controls the orientation of the grid.

• We need to customize GridBagConstraints objects to use GridBagLayout effectively


associated with its components.

• Customization of a GridBagConstraints object can be doneby setting one or more of its


instance variables.

• gridx & gridy

45
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

• The initial address of cell of a grid is gridx = 0 and gridy = 0.

• gridwidth & gridheight

• gridwidth constraint specifies the number of cells in a row and gridheight


specifies number of columns in display area of the components. The default
value is 1.

• fill

• GridBagConstraints.NONE (default value–does not grow when the window


is resized)

• GridBagConstraints.HORIZONTAL (this value fills all the horizontal display


area of a component, but it does not change height).

• GridBagConstraints.VERTICAL (it changes the height of a component, but


does not change its width)

• GridBagConstraints.BOTH (makes the component fill its display area


horizontally and vertically, both).

• ipadx and ipady

• for internal padding of components in given layout.

• Insets

• used for spacing between the component and the edges of its display area

• anchor

• specifies the position of a component in its display area

• weight x & weight y

• used to distribute space (horizontal and vertical)

Example

import java.awt.*;

public class GBLayoutDemo1 extends Frame{

public GBLayoutDemo1(){

46
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

setLayout(new GridBagLayout());

setTitle(“GridBagLayout Without Constraints”);

Label l=new Label(“Name”);

add(l);

TextField t=new TextField();

add(t);

Button b=new Button(“Submit”);

add(b);

Button b1=new Button(“Reset”);

add(b1);

setSize(200,200); setVisible(true);}

public static void main(String args[]){

GBLayoutDemo1 d=new GBLayoutDemo1();}}

Output

Menu

• Menu is a class which inherits MenuItem class and two interfaces:

47
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

– MenuContainer and

– Accessible.

• Menubar deploys a menu object which is a dropdown menu component.

– It shows a list of menu choices.

• To implement this concept we use three classes:

– MenuBar,

– Menu, and

– MenuItem.

Example

import java.awt.event.*;

import java.awt.*;

public class DemoMenu extends Frame implements ActionListener{

public void demoMenu() {

setTitle(“MenuDemo”);

setSize(250,150);

MenuBar menuBar = new MenuBar();

setMenuBar(menuBar);

MenuShortcut n=new MenuShortcut(KeyEvent.VK_N);

MenuShortcut o=new MenuShortcut(KeyEvent.VK_O);

MenuShortcut x=new MenuShortcut(KeyEvent.VK_X);

Menu fileMenu = new Menu(“File”);

Menu editMenu = new Menu(“Edit”);

MenuItem newAction = new MenuItem(“New”,n);

MenuItem openAction = new MenuItem(“Open”,o);

48
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

MenuItem exitAction = new MenuItem(“Exit”,x);

MenuItem cutAction = new MenuItem(“Cut”);

MenuItem copyAction = new MenuItem(“Copy”);

MenuItem pasteAction = new menuItem(“Paste”);

newAction.addActionListener(this);

openAction.addActionListener(this);

exitAction.addActionListener(this);

fileMenu.addSeparator();

fileMenu.add(newAction);

fileMenu.addSeparator();

fileMenu.add(openAction);

fileMenu.addSeparator();

fileMenu.add(exitAction);

menuBar.add(fileMenu);

cutAction.addActionListener(this);

copyAction.addActionListener(this);

pasteAction.addActionListener(this);

editMenu.add(cutAction);

editMenu.addSeparator();

editMenu.add(copyAction);

editMenu.addSeparator();

editMenu.add(pasteAction);

editMenu.addSeparator();

menuBar.add(editMenu);

setVisible(true);
49
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){

System.exit(0);}}); }

public void actionPerformed(ActionEvent e) {

String action=e.getActionCommand();

if(action.equals(“New”)){

System.out.println(“New”);}

else if(action.equals(“Open”)){

System.out.println(“File”);}

else if(action.equals(“Exit”)){

System.exit(0);}

else if(action.equals(“Cut”)){

System.out.println(“Cut”);}

else if(action.equals(“Copy”)){

System.out.println(“Copy”);}

else if(action.equals(“Paste”)){

System.out.println(“Paste”);}}

public static void main(String[] args) {

DemoMenu demo= new DemoMenu();

demo.demoMenu();} }

Output

50
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

Scrollbar

• Scrollbars are used to select continuous values through a range of integer values (the
range set between maximum and minimum).

• These scrollbars can either be set horizontally or vertically.

• The scrollbar’s maximum and minimum values can be set along with line increments and
page increments.

– Scrollbar() throws HeadlessException

– Scrollbar(int direction) throws HeadlessException

– Scrollbar(int direction, int initValue, int pageSize, int min, int max) throws
HeadlessException

Example

import java.awt.*;

import java.awt.event.*;

public class ScrollbarDemo extends Frame implements AdjustmentListener { Scrollbar


HScroll, VScroll;

Label lbl;

int X=100,Y=150;

public ScrollbarDemo () {

51
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

HScroll = new Scrollbar (Scrollbar.HORIZONTAL);

VScroll = new Scrollbar (Scrollbar.VERTICAL);

lbl = new Label (“”,Label.CENTER);

HScroll.setMaximum (400);

VScroll.setMaximum (400);

setBackground (Color.cyan);

setTitle(“Oval size changes with scrollbar movements”);

setLayout (new BorderLayout());

add (lbl,BorderLayout.NORTH);

add (HScroll,BorderLayout.SOUTH);

add (VScroll, BorderLayout.EAST);

HScroll.addAdjustmentListener (this);

VScroll.addAdjustmentListener (this);

HScroll.setValue (X); VScroll.setValue (Y);

lbl.setText (“HScroll = “ + HScroll.getValue() + “, VScroll = “ + VScroll


getValue());

setSize(500,500); setVisible(true);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){ System.exit(0);} });}

public void adjustmentValueChanged(AdjustmentEvent e) {

X=HScroll.getValue(); Y= VScroll.getValue ();

lbl.setText (“HScroll = “ + X + “, VScroll = “ + Y);

repaint();}

public void paint (Graphics g) {

g.drawOval (50, 60, X, Y); }

52
Dr. P.M.Manohar, Dept. of CSE, Raghu Engineering College(A), Visakhapatnam OOPS
through
Java –
Unit 5

public static void main(String args[]) {

ScrollbarDemo d=new ScrollbarDemo();}}

Output

53

You might also like