0% found this document useful (0 votes)
14 views38 pages

Awt Control

awt controls in java
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)
14 views38 pages

Awt Control

awt controls in java
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/ 38

USING AWT LAYOUT

MANAGERS & MENUS

Types of Control
ScrollBar,TextField,TextArea.
UnderstandingLayout Managers
Menu Bars and Menus
Dialog Boxes
File Dialog
ScrollBars
Scroll bars are used to select continuous values
between a specified minimum and maximum.
Scroll bars may be oriented horizontally or
vertically.A scroll bar is actually a composite of
several individual parts.
Each end has an arrow that we can click to move
the current value of the scroll bar one unit in the
direction of the arrow.
The current value of the scroll bar relative to its
minimum and maximum values is indicated by the
slider box (or thumb) for the scroll bar.
The slider box can be dragged by the user to a new
position. The scroll bar will then reflect this value.
Constructors:
Scrollbar( ):-creates a vertical scroll bar.
Scrollbar(int style):-allow us to specify the
orientation of the scroll bar. If style is
Scrollbar.VERTICAL, a vertical scroll bar is created.
If style is, Scrollbar.HORIZONTAL the scroll bar is
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:-
GETVALUE( ):-TO OBTAIN THE CURRENT VALUE OF THE SCROLL BAR.
SETVALUE( ):- IT THE CURRENT SETTING. FOR SETTING THE CURRENT
VALUE.
THESE METHODS ARE AS FOLLOWS:
INT GETVALUE( )
VOID SETVALUE(INT NEWVALUE)
WE CAN ALSO RETRIEVE THE MINIMUM AND MAXIMUM VALUES VIA
GETMINIMUM( ) AND GETMAXIMUM( ), SHOWN HERE:
INT GETMINIMUM( )
INT GETMAXIMUM( )
SETUNITINCREMENT( ):- BY DEFAULT, PAGE-UP AND PAGE-DOWN
INCREMENTS ARE 10.
SETBLOCKINCREMENT( ):- YOU CAN CHANGE THIS VALUE
THESE METHODS ARE SHOWN HERE:
VOID SETUNITINCREMENT(INT NEWINCR)
VOID SETBLOCKINCREMENT(INT NEWINCR)
EXAMPLE:-
IMPORT JAVA.AWT.*;
IMPORT JAVA.APPLET.*;
PUBLIC CLASS SBDEMO EXTENDS APPLET
{
STRING MSG = "";
SCROLLBAR VERTSB, HORZSB;
PUBLIC VOID INIT()
{
INT WIDTH = INTEGER.PARSEINT(GETPARAMETER("WIDTH"));
INT HEIGHT = INTEGER.PARSEINT(GETPARAMETER("HEIGHT"));
VERTSB = NEW SCROLLBAR(SCROLLBAR.VERTICAL,
0, 1, 0, HEIGHT);
HORZSB = NEW SCROLLBAR(SCROLLBAR.HORIZONTAL,
0, 1, 0, WIDTH);
ADD(VERTSB); ADD(HORZSB);
}
PUBLIC VOID PAINT(GRAPHICS G)
{
MSG = "VERTICAL: " + VERTSB.GETVALUE();
MSG += ", HORIZONTAL: " + HORZSB.GETVALUE();
G.DRAWSTRING(MSG, 6, 160);
}
}
TEXT FIELDS
 The TextField class implements a single-line text-
entry area, usually 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 control.
Constuctor:-
 TextField( ):-creates a default text field.

 TextField(int numChars):-creates a text field that is


numChars characters wide.
 TextField(String str):-initializes the text field with
the string contained in str.
 TextField(String str, int numChars):-initializes a text
field and sets its width
METHODS
 obtain the string currently contained in the text field getText( ).
 For setting the text, setText( ).
String getText( )
void setText(String str)
 The user can select a portion of the text in a text field. Also, we can
select a portion of text under program control by using select( ).
 Our program can obtain the currently selected text by calling the
getSelectedText( ).
String getSelectedText( )
void select(int startIndex, int endIndex)
 We can control whether the contents of a text field may be modified
by the user by calling setEditable( ).
 We can determine editability by calling isEditable( ).
boolean isEditable( )
void setEditable(boolean canEdit)
 void setEchoChar(char ch):- disable the echoing of the characters as
they are typed
Boolean echoCharIsSet( ):-check with the actual characters typed
char getEchoChar( ):- retrieve the echo character.
EXAMPLE
import java.awt.*;
import java.applet.*;
public class TextFieldDemo extends Applet
{
TextField name, pass;
public void init()
{
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
}
public void paint(Graphics g){ }
}
TEXT AREA
 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 calledTextArea.
 Constructors for 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
 TextArea is a subclass of TextComponent. Therefore,
it supports the getText( ), setText( ),
getSelectedText( ), select( ), isEditable( ), and
setEditable( ) methods .
 TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int
endIndex)
The append( ) method appends the string specified by
str to the end of the current text.
The insert( ) inserts the string passed in str at the
specified index.
In order to replace text, we call replaceRange( ).
It replaces the characters from startIndex to
endIndex–1, with the replacement text passed in
EXAMPLE
import java.awt.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " +"a Software
design.\n" + "One way is to make it so simple\n" + "that there are
obviously no deficiencies.\n" + "And the other way is to make it so
complicated\n" + "that there are no obvious deficiencies.\n\n" + "
-C.A.R. Hoare\n\n" + "There's an old story about the person who
wished\n" +"his computer were as easy to use as his
telephone.\n" +"That wish has come true,\n" +"since I no longer
know how to use my telephone.\n”;
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
LAYOUT MANAGERS
 A layout manager automatically arranges your controls
within a window instead of laying out your controls by
hand.
 Avoiding manually laying out for 2 main reasons: *
Tedious task to layout large number of components.
* Width & Height information is not yet available when
arranging some control.
Layout Managers at work :-
WHAT IT IS???????
C Each Container has a layout manager
associated with it.
C A layout manager is an instance of any class that
implements the LayoutManager interface.
C The layout manager is set by the setLayout( )
method.
C Whenever a container is resized(or sized for the
first time), the layout manager is used to position
each components within it.
……MORE ABOUT

 The setLayout( ) method has the following general form:


void setLayout(LayoutManager layoutObj)
 Here, layoutObj is a reference to the desired layout manager.
 The layout manager is notified each time you add a
component to a container.
 The layout manager is consulted by the following methods
 minimumLayoutSize( )
 preferredLayourSize( )
whenever the container needs to be resized.
 Each component that is being managed by a layout
manager contains the
 getPreferredSize( )
 getMinimumSize( ) – to display each component
with the prefered and minimum size required.
 Java has several predefined LayoutManager classes
LIST OF PREDEFINED
LAYOUTS
å FLOW LAYOUT
å BORDER LAYOUT

USING INSETS
å GRID LAYOUT
FLOW LAYOUT
õ FlowLayout is the default layout
manager.
õ Implements 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.
õ Fits to line. If not, appears in next line.

õ Small spaces b/w each component;


▲&▼,►&◄.
CONSTRUCTORS FOR
FLOWLAYOUT
 FlowLayout( ) – creates the default layout which
centers components and leaves five pixels of space
b/w each component.
 FlowLayout(int ) – To specify how each line
is aligned. Valid values are:
FlowLayout.LEFT  for left alignment.
FlowLayout.RIGHT  for right alignment.
FlowLayout.CENTER  for center alignement.
 FlowLayout(int , int , int ) – To
specify horizontal or vertical space between
components.
EXAMPLE FOR FLOWLAYOUT
public class FlowLayoutDemo 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");
setLayout(new FlowLayout(FlowLayout.CENTER));
add(Win98);
add(winNT);
add(solaris);
add(mac);
}public void paint(Graphics g){ }}
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 north,
south, east and west.
 The middle area is called the center.
CONSTRUCTORS FOR BORDERLAYOUT
 BorderLayout( ) – creates a default border layout.
 BorderLayout(int horz,int vert) – allows you to
specify the horizontal and vertical space left between
components.
 When adding components:
void add(Component compObj, Object region);
 compObj is the component to be added, region
specifies where the component will be added.
 BorderLayout defines the following constants that
specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH.
EXAMPLE FOR BORDERLAYOUT
import java.awt.*;
import java.applet.*;
import java.util.*;
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 might go here."), 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 reasonable one persists in " + "trying to adapt the world to himself.
\n" +"therefore all progress depends \n \n";
add(new TextArea(msg), BorderLayout.CENTER);}}
OUTPUT:
USING INSETS

 Sometimes U’ll want to leave a small amount of space b/w


the container that holds your components and the window
that contains it.
 To do this, override the getInsets( ) method.

 The constructor for Insets is shown here:

Insets(int top, int left, int bottom, int right)


 The values passed in are to specify the amount of space b/w
the container and its enclosing window.
 The general form:

Insets getInsets( )
 When overriding one of these methods, you must return a
new Insets object that contains the inset spacing you desire.

EXAMPLE :
// Demonstrate BorderLayout with Insets
import java.awt.*;
import java.applet.*;
import java.util.*;
public class BorderLayoutDemo extends Applet {
public void init()
{
setBackground(Color.Cyen);
setLayout(new BorderLayout());
add(new Button("This is across the top."), BorderLayout.NORTH);
add(new Label("The footer message might go here."),
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 reasonable one persists in " + "trying to adapt the world to himself.
\n" +
"therefore all progress depends \n \n“;
add(new TextArea(msg), BorderLayout.CENTER);
}
public Insets getInsets() {
return new Insets(10,10,10,10);
}
}
VERSUS
GRIDLAYOUT
 GridLayout lays out components in a two-
dimensional grid.
 When you instantiate a GridLayout, you define the
number of rows and columns.
 The constructors supported by GridLayout are:
 GridLayout( ) – Creates a single-column grid layout.
 GridLayout(int numRows, int numColumns) –
Creates a grid layout with the specified number of
rows and columns.
 GridLayout(int numRows, int numColumns, int
horz, int vert) – Allows you to specify the horizontal
& vertical space left b/w components.
 Specifying numRows as Zero allows for unlimited-
length columns and viceversa for numColumns as Zero.
SAMPLE PROGRAM

// Demonstrate GridLayout

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)); }
}}}
CARD LAYOUT
 The CardLayout class is unique among the other layout
managers in that it stores several different layouts.
 CardLayout Provides these two constructors.
CardLayout()
CardLayout(int horz, int vert)
 Use of a CardLayout requires a bit more than the other
layouts. The cards are typically held in an object of type Panel.
 You must create a panel that contains the deck and a panel for
each card in the deck.
 Next, you add to the appropriate panel the components that
form each card.
 Then add these panels to the panel for which CardLayout is
the layout manager.
 Add this panel to the main applet panel.
 After this, u must provide some way for the user to select
between cards.
 Common approach is to include one push button for each card
in the deck.
 When adding cards to a panel.
 void add(Component panelObj, Object name);
 name is the string that specifies the name of the card
and panelObj is for specifying the panel.
 After the creation of the deck, ur prog. activates a card
by calling one of the following methods defined by
CardLayout.
 void first(Container deck) – causes the first card in
the deck to be shown).
 void last(Container deck), void next(Container
deck), void previous(Container deck) llly…
 void show(Container deck, String name) –
displays the card whose name is passed in the
cardName.
 deck – the container that holds the cards, cardName
is the name of a card.

Example
MENU BARS AND MENUS
 A top-level window can have a menu bar associated with it. A
menu bar displays a list of top-level menu choices. Each choice
is associated with a drop-down 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.
Since Menu is a subclass of MenuItem, a hierarchy of nested
submenus can be created.
 It is also possible to include checkable menu items. These are
menu options of type CheckboxMenuItem and will have a
check mark next to them when they are selected.
 For creating a menu bar, we first create an instance of
MenuBar. This class only defines the default constructor. Next,
create instances of Menu that will define the selections
displayed on the bar.
CREATING MENU ON FRAME

Create Add Add Menu


Menubar Menu object MenuItems Bar To
Object to Menu Applet
CONSTRUCTOR
 Menu( )
 Menu(String optionName)
 Menu(String optionName, boolean removable):-If
removable is true, the pop-up menu can be removed
and allowed to float free. Otherwise,it will remain
attached to the menu bar.
It defines these constructors:
 MenuItem( )
 MenuItem(String itemName)
 MenuItem(String itemName, MenuShortcut
keyAccel)
 CheckboxMenuItem( ):-the checkable entry is
unchecked
 CheckboxMenuItem(String itemName)
 CheckboxMenuItem(String itemName, boolean on):-if
on is true, the checkable entry is initially checked.
Otherwise, it is cleared.
METHOD
 We can disable or enable a menu item by using
thesetEnabled( ) method.
void setEnabled(boolean enabledFlag)
 If the argument enabledFlag is true, the menu
item is enabled. If false,the menu item is disabled.
We can determine an item’s status by calling
isEnabled( ).
boolean isEnabled( )
 We can change the name of a menu item by
calling setLabel( ).
 We can retrieve the current name by using
getLabel( ).
void setLabel(String newName)
String getLabel( )
EXAMPLE mbar.add(file);
import java.awt.*; Menu edit = new Menu("Edit");
import java.applet.*; MenuItem item6, item7, item8, item9;
class MenuFrame extends Frame{ edit.add(item6 = new MenuItem("Cut"));
String msg = ""; edit.add(item7 = new MenuItem("Copy"));
CheckboxMenuItem debug, test; edit.add(item8 = new MenuItem("Paste"));
MenuFrame(String title){ edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
super(title);
MenuItem item10, item11, item12;
// create menu bar and add it to frame
sub.add(item10 = new MenuItem("First"));
MenuBar mbar = new MenuBar();
sub.add(item11 = new MenuItem("Second"));
setMenuBar(mbar); sub.add(item12 = new MenuItem("Third"));
// create the menu items edit.add(sub);
Menu file = new Menu("File"); // these are checkable menu items
MenuItem item1, item2, item3, item4, item5; debug = new CheckboxMenuItem("Debug");
file.add(item1 = new MenuItem("New...")); edit.add(debug);
file.add(item2 = new MenuItem("Open...")); test = new CheckboxMenuItem("Testing");
edit.add(test);
file.add(item3 = new MenuItem("Close"));
mbar.add(edit);
file.add(item4 = new MenuItem("-"));
}
file.add(item5 = new MenuItem("Quit..."));
}  o/p
public class MenuDemo extends Applet
{
Frame f;
public void init()
{
f = new MenuFrame("Menu Demo");
f.setVisible(true);
int width =
Integer.parseInt(getParameter("width"));
int height =
Integer.parseInt(getParameter("height"));
setSize(width, height);
f.setSize(width, height);
}
public void start()
{
f.setVisible(true);
}
public void stop()
{
f.setVisible(false);
}
}
DIALOG BOXES
 Dialog boxes are primarily used to obtain user input. They
are similar to frameWindows, except that dialog boxes are
always child windows of a top-level window. Also, dialog
boxes don’t have menu bars. In other respects, dialog boxes
function like frame windows.
 Dialog boxes may be modal or modeless.

 When a modal dialog box is active, all input is directed to it


until it is closed. This means that we cannot access other
parts of our program until we have closed the dialog box.
 When a modeless dialog box is active,input focus can be
directed to another window in our program. Thus, otherparts
of our program remain active and accessible. Dialog boxes
are of typeDialog.
Two commonly used constructors are shown here:
 Dialog(Frame parentWindow, boolean mode)

 Dialog(Frame parentWindow, String title, boolean mode)


FILEDIALOG
 Java provides a built-in dialog box that lets the user
specify a file. To create a file dialog box, instantiate
an object of type FileDialog. This causes a file dialog
box to be displayed.
FileDialog provides these constructors:
 FileDialog(Frame parent, String boxName)
 FileDialog(Frame parent, String boxName, int how)
 FileDialog(Frame parent)
If how is FileDialog.LOAD, then the box is selecting a
file for
reading. If how is FileDialog.SAVE, the box is selecting
a file for writing. The third constructor creates a
dialog box for selecting a file for reading.
 FileDialog( ) provides methods that allows us to
determine the name of the file and its path as
selected by the user. Here are two examples:
String getDirectory( )
String getFile( )
EXAMPLE
import java.awt.*;
class SampleFrame extends Frame
{
SampleFrame(String title)
{
super(title);
}
}
class FileDialogDemo
{
public static void main(String args[])
{
Frame f = new SampleFrame("File Dialog Demo");
f.setSize(100, 100);
FileDialog fd = new FileDialog(f, "File Dialog");
fd.setVisible(true);
}
}

You might also like