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

3042 - File - JAVA - Notes (Unit 4)

Uploaded by

ajith channel
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)
211 views

3042 - File - JAVA - Notes (Unit 4)

Uploaded by

ajith channel
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/ 18

SRI KALISWARI COLLEGE (Autonomous), SIVAKASI

DEPARTMENT OF COMPUTER APPLICATIONS


CORE COURSE – V: JAVA PROGRAMMING (23UCAC31)

UNIT – IV
AWT Controls: The AWT Class Hierarchy – User Interface Components – Labels –
Button – Text Components – Check Box – Check Box Group – Choice – List Box – Panels –
Scroll Pane – Menu – Scroll Bar. Working with Frame Class – Colour – Fonts and Layout
Managers. Event Handling: Events – Event Sources – Event Listeners – Event Delegation
Model (EDM) – Handling Mouse and Keyboard Events – Adapter Classes – Inner Classes.

JAVA AWT

 Java AWT (Abstract Window Toolkit) is an API used to create Graphical User
Interface (GUI) or Windows-based Java programs
 Java AWT components are platform-dependent.
 The java.awt package contains AWT API classes

The AWT Class Hierarchy

 Components: AWT provides various components such as buttons, labels, text


fields, checkboxes, etc used for creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels, frames, and dialogues to
organize and group components in the Application.
 Layout Managers: Layout Managers are responsible for arranging data in the
containers some of the layout managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the events like mouse clicks, key
presses, etc. using event listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that helps to draw shapes,
insert images and write text in the components of a Java Application.

Types of Containers in Java AWT

There are four types of containers in Java AWT:

1. Window: Window is a top-level container that represents a graphical window or


dialog box. The Window class extends the Container class, which means it can
contain other components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be
used for grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can
have menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve
user input.

*************************

User Interface Components

1. Labels

 Label is used to display the static text


 Labels are passive controls that do not support any interaction with the user

Constructors to Create Label

 Label( ) - Creates a blank label


 Label(String str) - creates a label that contains the string specified by str. This
string is left-justified
 Label(String str, int how) - creates a label that contains the string specified by
str using the alignment specified by how. The value of how must be one of these
three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

Methods of Label Control

 void setText(String str)


 String getText( )
 void setAlignment(int how)
 int getAlignment( )

Example
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}

******************
2. Buttons
 The most widely used control is the push button.
 A push button is a component that contains a label and that generates an event
when it is pressed.
 Push buttons are objects of type Button.
Constructors for Button Control
Button defines these two constructors:
 Button( )
 Button(String str)
Methods for Button Control
 String getLabel()
 void setLabel(String str)
 void setEnabled(Boolean enable)
 Void addActionListener(ActionListener l)
 void removeActionListener(ActionListener l)
 String getActionCommand()
 void setActionCommand(String Cmd)
Example
import java.awt.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet
{
String msg = "";
Button yes, no, maybe;
public void init()
{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button(“Understand");
add(yes);
add(no);
add(maybe);
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}
}

********************
3. Check Box
 Control which allows the user to choose more than one option
Constructors for Check Box Control
 Checkbox( )
 Checkbox(String str)
 Checkbox(String str, boolean on)
 Checkbox(String str, boolean on, CheckboxGroup cbGroup)
 Checkbox(String str, CheckboxGroup cbGroup, boolean on)
Methods for Check Box Control
 boolean getState( )
 void setState(boolean on)
 String getLabel( )
 void setLabel(String str)
 void addItemListener(ItemListener l)
 void removeItemListener(ItemListener l)
Example
import java.awt.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
public void init()
{
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
add(Win98);
add(winNT);
add(solaris);
add(mac);
}
public void paint(Graphics g)
{}
}
*********************
4. Checkbox Group
 It is possible to create a set of mutually exclusive check boxes in which one and
only one check box in the group can be checked at any one time.
 These check boxes are often called radio button.
 Check box groups are objects of type CheckboxGroup.
 Only the default constructor is defined, which creates an empty group.
Methods for Checkbox Group Control
 Checkbox getSelectedCheckbox( )
 void setSelectedCheckbox(Checkbox wh)
Example
import java.awt.*;
import java.applet.*;
/*
<applet code="CBGroup"
width=250 height=200>
</applet>
*/
public class CBGroup extends Applet
{
String msg = "";
Checkbox Win98, winNT,
solaris, mac;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("MacOS", cbg, false);
add(Win98); add(winNT);
add(solaris); add(mac);
}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
5. Choice Control

 The Choice class is used to create a pop-up list of items from which the user may
choose.
 Thus, a Choice control is a form of menu.
 Each item in the list is a string that appears as a left justified label in the order it
is added to the Choice object.

Methods for Choice Control

 void add(String name)


 String getSelectedItem( )
 int getSelectedIndex( )
 int getItemCount( )
 void select(int index)
 void select(String name)
 String getItem(int index)

Example

import java.awt.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=180>
</applet>
*/
public class ChoiceDemo extends Applet
{
Choice os, browser;
String msg = "";
public void init()
{
os = new Choice();
browser = new Choice();
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer 4.0");
browser.add("Internet Explorer 5.0");
browser.add("Internet Explorer 6.0");
browser.add("Lynx 2.4");
browser.select("Netscape 4.x");
add(os);
add(browser);
}
public void paint(Graphics g)
{}}

**************************

6. List Control
 The List class provides a compact, multiple-choice, scrolling selection list.
 Unlike the Choice object, which shows only the single selected item in the menu,
a List object can be constructed to show any number of choices in the visible
Window.
 It can also be created to allow multiple selections.
Constructors for List Control
 List( ) - creates a List control that allows only one item to be selected at any one
time
 List(int numRows) - the value of numRows specifies the number of entries in
the list that will always be visible
 List(int numRows, boolean multipleSelect) - if multipleSelect is true, then the
user may select two or more items at a time
Methods for List Control
 void add(String name)
 void add(String name, int index)
 String getSelectedItem( )
 int getSelectedIndex( )
 String[ ] getSelectedItems( )
 int[ ] getSelectedIndexes( )
 int getItemCount( )
 void select(int index)
 String getItem(int index)
***********************
7. Scroll Bar
 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.
o slider box (or thumb) for the scroll bar.
 The slider box can be dragged by the user to a new position, this action
translates into some form of page up and page down.
Constructors for Scroll Bar
 Scrollbar( ) - creates a vertical scroll bar
 Scrollbar(int style) - Allow us to specify style Scrollbar.VERTICAL,
Scrollbar.HORIZONTAL
 Scrollbar(int style, int iValue, int tSize, int min, int max) - The initial value of
the scroll bar is passed in iValue. The number of units represented by the height
of the thumb is passed in tSize. The minimum and maximum values for the scroll
bar are specified by min and max
Methods for Scroll Bar
 void setValues(int iValue, int tSize, int min, int max)
 int getValue( )
 void setValue(int newValue)
 int getMinimum( )
 int getMaximum( )
 void setUnitIncrement(int newIncr)
 void setBlockIncrement(int newIncr)

**************************
8. Text Component
 It is used to get the input from user
 There are 2 types of text component
1. Textfield
2. Textarea
1. Textfield
 The TextField class implements a single-line text-entry area, called an edit
control.
 Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections.
 TextField is a subclass of TextComponent.
Constructors for Textfield Control
 TextField( )
 TextField(int numChars)
 TextField(String str)
 TextField(String str, int numChars)
Methods for Textfield Control
 String getText( )
 void setText(String str)
 String getSelectedText( )
 void select(int startIndex, int endIndex)
 boolean isEditable( )
 void setEditable(boolean canEdit)
 void setEchoChar(char ch)
 boolean echoCharIsSet( )
 char getEchoChar( )
2. Textarea
 Sometimes a single line of text input is not enough for a given task. To handle
these situations, the AWT includes a simple multiline editor called TextArea.
Following are the constructors for TextArea:
 TextArea( )
 TextArea(int numLines, int numChars)
 TextArea(String str)
 TextArea(String str, int numLines, int numChars)
 TextArea(String str, int numLines, int numChars, int sBars)
Methods for Textarea Control
 TextArea is a subclass of TextComponent.
 Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ),
isEditable( ), and setEditable( ) methods as of TextField.
 TextArea adds the following methods:
 void append(String str)
 void insert(String str, int index)
 void replaceRange(String str, int startIndex, int endIndex)
******************************
Menu Bars and Menus
 A menu bar displays a list of top-level menu choices. Each choice is associated
with a dropdown menu.
 This concept is implemented in Java by the following classes:
MenuBar, Menu, and MenuItem.
 In general, a menu bar contains one or more Menu objects. Each Menu object
contains a list of MenuItem objects.
 Each MenuItem object represents something that can be selected by the user.
 MenuBar Class Defines only default constructor.
 Menu Class Constructors
1. Menu( )
2. Menu(String optionName)
3. Menu(String optionName, boolean removable)
 Here, optionName specifies the name of the menu selection.
 Individual menu items constructors:
1. MenuItem( )
2. MenuItem(String itemName)
3. MenuItem(String itemName, MenuShortcut keyAccel)
Methods
 Disable or enable a menu item by using:
1. void setEnabled(boolean enabledFlag)
2. boolean isEnabled( )
 Label set and get using:
1. void setLabel(String newName)
2. String getLabel( )
 Checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem:
1. CheckboxMenuItem( )
2. CheckboxMenuItem(String itemName)
3. CheckboxMenuItem(String itemName, boolean on)
 Status about checkable MenuItem:
1. boolean getState( )
2. void setState(boolean checked)
 For add MenuItem:
1. MenuItem add(MenuItem item)
 For add MenuBar
1. Menu add(Menu menu)
 To get Item from Menu:
1. Object getItem( )
Example
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu 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();
} }
************************
Layout Managers
 Layout means arranging the components within the container.
 The task of lay outing can be done automatically by the Layout manager.
 The layout manager is set by the setLayout( ) method.
 If no call to setLayout( ) is made, then the default layout manager is used.
 Whenever a container is resized (or sized for the first time), the layout manager
is used to position each of the components within it.
 The setLayout( ) method has the following general form:
 void setLayout(LayoutManager layoutObj)
 Here, layoutObj is a reference to the desired layout manager.
 If we wish to disable the layout manager and position components manually,
pass null for layoutObj.
 There are following classes that represents the layout managers:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout

1. Flow Layout

 FlowLayout is the default layout manager.


 FlowLayout implements a simple layout style, which is similar to how words
flow in a text editor.
 Components are laid out from the upper-left corner, left to right and top to
bottom.
 When no more components fit on a line, the next one appears on the next line.
 A small space is left between each component, above and below, as well as left
and right.

Constructors for FlowLayout

 FlowLayout( ) - centers components and leaves five pixels of space between


each component.
 FlowLayout(int how) - lets us specify how each line is aligned. Valid values for
how are as follows:
1. FlowLayout.LEFT
2. FlowLayout.CENTER
3. FlowLayout.RIGHT
 FlowLayout(int how, int horz, int vert) - allows us to specify the horizontal
and vertical space left between components

Example

public class FlowLayoutDemo extends Applet


{

Checkbox Win98, winNT, solaris, mac;

public void init()

Win98 = new Checkbox("Windows 98/XP", null, true);

winNT = new Checkbox("Windows NT/2000");

solaris = new Checkbox("Solaris");

mac = new Checkbox("MacOS");

setLayout(new FlowLayout(FlowLayout.CENTER));

add(Win98); add(winNT);add(solaris);add(mac);

}}

2. Border Layout

 The BorderLayout class implements a common layout style for top-level


windows.
 It has four narrow, fixed-width components at the edges and one large area in
the center.
 The four sides are referred to as
1. north,
2. south,
3. east, and
4. west.
 The middle area is called the center.
 BorderLayout defines the following constants that specify the regions:
1. BorderLayout.CENTER
2. BorderLayout.SOUTH
3. BorderLayout.EAST
4. BorderLayout.WEST
5. BorderLayout.NORTH
 To add components, we use these constants with the following form of add( ),
which is defined by Container:
void add(Component compObj, Object region);
 Here, compObj is the component to be added, and region specifies where the
component will be added.

Constructors for Border Layout

 BorderLayout( ) - creates a default border layout


 BorderLayout(int horz, int vert) - allows us to specify the horizontal and
vertical space left between components in horz and vert, respectively

Example
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."), BorderLayout.NORTH);
add(new Label("The footer message."), BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts himself to the world;\n" +
"the unreasonable one persists in trying to adapt the world to himself.\n"
+
"Therefore all progress depends on the unreasonable man.\n\n" + " -
George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}

3. Grid Layout

 GridLayout lays out components in a two-dimensional grid.


 When we instantiate a GridLayout, we define the number of rows and columns.

Constructors for Grid Layout

 GridLayout( ) - creates a single-column grid layout


 GridLayout(int numRows, int numColumns ) - creates a grid layout with
specified number of rows and columns
 GridLayout(int numRows, int numColumns, int horz, int vert)

Example

public class GridLayoutDemo extends Applet {

static final int n = 4;

public void init(){

setLayout(new GridLayout(n, n));

setFont(new Font("SansSerif", Font.BOLD, 24));

for(int i = 0; i < n; i++){

for(int j = 0; j < n; j++){

int k = i * n + j;
if(k > 0)

add(new Button("" + k));

} }}}

4. Card Layout

 The CardLayout class is unique among the other layout managers in that it stores
several different layouts.
 Each layout can be thought of as being on a separate index card in a deck that can
be shuffled so that any card is on top at a given time.
 This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input.
 We can prepare the other layouts and have them hidden, ready to be activated
when needed

Constructors for Card Layout

CardLayout provides these two constructors:

 CardLayout( ) - creates a default card layout


 CardLayout(int horz, int vert) - allows us to specify the horizontal and vertical
space left between components

Methods

 void add(Component panelObj, Object name);


 Here name is a string that specifies the name of the card whose panel is specified
by panelObj. After we have created a deck, our program activates a card by
calling one of the following methods:
1. void first(Container deck)
2. void last(Container deck)
3. void next(Container deck)
4. void previous(Container deck)
5. void show(Container deck, String cardName)
 deck is a reference to the container (usually a panel) that holds the cards, and
cardName is the name of a card.

Example

import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample extends Frame implements ActionListener{
CardLayout card;
Button b1,b2,b3;
CardLayoutExample(){
card=new CardLayout(40,30);
setLayout(card);
b1=new Button("Apple");
b2=new Button("Boy");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1,”card1”); add(b2,”card2”); add(b3,”card3”); }
public void actionPerformed(ActionEvent e) {
card.next(this);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
} }

5. GridBag Layout
 Each GridBagLayout object maintains a dynamic rectangular grid of cells, with
each component occupying one or more cells, called its display area.
 Each component managed by a grid bag layout is associated with an instance of
GridBagConstraints that specifies how the component is laid out within its
display area
 For customize a GridBagConstraints object by setting one or more of its instance
variables:
 gridx, 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.
 gridwidth, gridheight: Specifies the number of cells in a row (for gridwidth) or
column (for gridheight) in the component's display area. The default value is 1.
 fill: Used when the component's display area is larger than the component's
requested size to determine whether (and how) to resize the component.

Example
import java.awt.*;
import java.util.*;
import java.applet.Applet;
public class GridBagEx1 extends Applet {
protected void makebutton(String name,
GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
add(button);
}
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
makebutton("Button1", gridbag, c);
makebutton("Button2", gridbag, c);
makebutton("Button3", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; //end row
makebutton("Button4", gridbag, c);
c.weightx = 0.0; //reset to the default
makebutton("Button5", gridbag, c); //another row
}
public static void main(String args[]) {
Frame f = new Frame("GridBag Layout Example");
GridBagEx1 ex1 = new GridBagEx1();
ex1.init(); f.add("Center", ex1); f.pack();
f.resize(f.preferredSize());
f.show(); } }

**************************
Working with Color
 Color is encapsulated by the Color class.
 Color defines several constants to specify a number of common colors.
 We can create our own colors, using one of the Color constructors.
 Color( int red, int green, int blue)
 Color( int rgbValue)
 Color( float red, float green, float blue)
 these values must be between 0 and 255.
 eg. new Color(255, 100, 100); //light red
Color Methods
Using Hue, Saturation and Brightness
 The Hue-Saturation-Brightness(HSB) color model is an alternative to Red-Green
Blue(RGB) for specifying particular colors.
Hue
 is a wheel of Color
 specified with a number between 0.0 and 1.0
 colors approximately red, orange, yellow, green, blue, indigo and violet.
Saturation
 scale ranging from 0.0 to 1.0 representing light pastels to intense hues.
Brightness
 range from 0.0 to 1.0 where 1 is bright white and 0 is black.

 Color supplies two methods to convert between RGB and HSB


o static int HSBtoRGB(float hue, float saturation, float brightness)
o static float[ ] RGBtoHSB(int red, int green, int blue, float values[ ])
 RGBtoHSB( ) returns a float array of HSB values corresponding to RGB integers
o the array contains the hue at index 0, saturation at index 1, and brightness
at index 2.
Setting the current Graphics Color
 void setColor(Color newColor)
o newColor -> specifies the new drawing color
 Color getColor( )
o to obtain the current color

*********************
Working with Fonts
 The AWT supports multiple type fonts.
 Fonts have a family name, a logical font name and a face name.
 family name -> general name of font. Eg. Courier
 logical name -> category of font. Eg. Monospaced
 face name -> specific font. Eg. Courier Italic
 Fonts are encapsulated by the Font class.
 Methods (refer book)
 The Font class defines these variables
 String name – name of the font
 float pointSize – size of the font in points
 int size – size of the font in points
 int style – font style
Determining the Available Fonts
 String[ ] getAvailableFontFamilyNames( )
 Font[ ] getAllFonts( )
Creating and Selecting a Font
 Font constructor
 Font(String fontName, int fontStyle, int pointSize)
 fontName
 name of the desired font
 Dialog, DialogInput, SansSerif, Serif and Monospaced supported by all Java
environments
 default -> Dialog
 fontStyle
 style of the font
 3 constants (Font.PLAIN, Font.BOLD, Font.ITALIC)
 can be ORed together
 eg. Font.BOLD | Font.ITALIC
 pointSize -> size of the font in points

Obtaining Font Information


 Font getFont( )
 To obtain information about the currently selected font.
 defined by the Graphics class

************************

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