0% found this document useful (0 votes)
20 views62 pages

Ajp CHP 1

Uploaded by

rahul13237
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)
20 views62 pages

Ajp CHP 1

Uploaded by

rahul13237
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/ 62

CHAPTER 1

Abstract Window Toolkit (AWT)


Outcomes
-> Develop GUI programs using AWT
components for the given problem.
-> Create Frame window with the specified
AWT components.
-> Arrange the GUI components using specified
layout managers.
-> Develop a program using menu and Dialog
Boxes for the given problem.
Introduction to AWT
Abstract Window Toolkit
The Abstract Window Toolkit was Java’s first
GUI Framework.
AWT provides classes and other tools for
building programs that have a graphical
user interface.
AWT classes are contained in the java.awt
package.
The term “Abstract” refers to the AWT’s
ability to run on multiple platforms.
AWT components are platform
dependent.
AWT Class Hierarchy
Component

At the top of the AWT hierarchy is the Component class.


It is an abstract class that encapsulates all of the attributes of a
visual component.
Components are generally the things that the user interacts with.
List of common Components
TextField
TextArea
List
Scrollbar
Choice
Button
Label
...
All containers
Useful Methods of Component class

Method Description

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

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

public void defines the layout manager for the container.


setLayout(LayoutManager m)

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


default false.
Container
Container is a subclass of Component. (ie. All
containers are themselves, Components)
Containers contain components such as buttons,
textfields, labels etc.
For a component to be placed on the screen, it
must be placed within a Container.
The classes that extends Container class are
known as container such as Frame, Dialog and
Panel.
The Container class defined all the data and
methods necessary for managing groups of
Components
Windows and Frames
The Window class defines a top-level Window with
no Borders or Menu bar.
You must use frame, dialog or another window for
creating a window.
Frame defines a top-level Window with Borders,
Title and Menu Bar.
Frames are more commonly used than Windows.
Once defined, a Frame is a Container which can
contain Components
Frame aFrame = new Frame(“Hello World”);
aFrame.setSize(100,100);
aFrame.setLocation(10,10);
aFrame.setVisible(true);
Creating a Graphical User Interface
• GUI programming in Java is based on three
concepts:
▫ Components. A component is an object that the user can
see on the screen and—in most cases—interact with.
▫ Containers. A container is a component that can hold
other components.
▫ Events. An event is an action triggered by the user, such as
a key press or mouse click.
• Designing a graphical user interface involves
creating components, putting them into containers,
and arranging for the program to respond to events.

9
Creating a Graphical User Interface
• Components are objects, so they’re created by
invoking a constructor.
• A button would be created by using a constructor
belonging to the Button class.
• The most commonly used constructor has one
argument (the button’s label):
Button b = new Button("Testing");
• For a component to be visible, it must be added
to a container (typically a frame) by the add
method.

10
Creating a Graphical User Interface

• To detect when an event occurs, a special


“listener” object can be attached to a component.
• When the user performs an action that involves
the component, a method belonging to the
listener object will be called automatically.

11
Frames
• In Java terminology, a frame is a window with a
title and a border.
• A frame may also have a menu bar.
• Frames play an important role in the AWT
because a GUI program normally displays a
frame when it’s executed.

12
The Frame Class
• Frames are created using one of the constructors in
the Frame class.
• One constructor takes a single argument (the title to
be displayed at the top of the frame):
Frame f = new Frame("Title goes here");
• Although the Frame object now exists, it’s not
visible on the screen.
• Before making the frame visible, a method should be
called to set the size of the frame.
• If desired, the frame’s location can also be specified.

13
Frame Methods
• Many methods used with Frame objects are
inherited from Window (Frame’s superclass) or
from Component (Window’s superclass).
• The setSize method sets the width and height
of a frame:
f.setSize(width, height);
• If a program fails to call setSize before
displaying a frame, it will assume a default size.

14
Frame Methods
• The size of a frame can change during the
execution of a program.
• The getSize method returns a frame’s current
width and height:
Dimension frameSize = f.getSize();
frameSize.width will contain f’s width.
frameSize.height will contain f’s height.

15
Frame Methods
• The setVisible method controls whether or
not a frame is currently visible on the screen.
• Calling setVisible with true as the argument
makes a frame visible:
f.setVisible(true);
• Calling it with false as the argument makes the
frame disappear from the screen:
f.setVisible(false);
• The Frame object still exists; it can be made to
reappear later by calling setVisible again.

16
Creating a Frame
• The FrameTest program creates a Frame
object and displays it on the screen.
• This program illustrates three key steps:
1. Using the Frame constructor to create a frame.
2. Setting the size of the frame.
3. Displaying the frame on the screen.

17
FrameTest.java
// Displays a frame on the screen.

import java.awt.*;
public class FrameTest
{
public static void main(String[] args)
{
Frame f = new Frame("Frame Test");
f.setSize(150, 100);
f.setVisible(true);
}
}

18
Creating a Frame
• Frame created by the FrameTest program:

• As with the other AWT components, the


appearance of a frame depends on the platform.

19
Creating a Frame
• Clicking on the Close button has no effect,
because there’s no action associated with that
button.
• The frame will have be closed the hard way, by
killing the program.
• In Windows, click on the DOS window from
which the program was launched, hold down the
Ctrl key, and press the letter C.

20
Setting the Location of a Frame
• By default, all windows (including frames) are
displayed in the upper-left corner of the screen,
which has coordinates (0,0).
• The setLocation method can be used to specify
a different location:
f.setLocation(50, 75);
• To find the current location of a frame, call
getLocation:
Point frameLocation = f.getLocation();
The coordinates of f’s upper-left corner will be
stored in frameLocation.x and
frameLocation.y.
21
Adding Components to a Frame
• To add a component to a frame (or any kind of
container), the add method is used.
• add belongs to the Container class, so it’s
inherited by Frame and the other container
classes.
• An example of adding a button to a frame:
Button b = new Button("Testing");
add(b);

22
Creating Frame by 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 visibl
}
public static void main(String args[])
{
First f=new First();
}
}
Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
Panels

The Panel is the container that doesn't contain title bar


and menu bars. It can have other components like
button, textfield etc.

Panel aPanel = new Panel();


aPanel.add(new Button("Ok"));
aPanel.add(new Button("Cancel"));
Buttons
• This class represents a push-button which displays some
specified text.

Constructors
1) Button()
Constructs a button with an empty string for its label.
2) Button(String text)
Constructs a new button with specified label.

Panel aPanel = new Panel();


Button okButton = new Button("Ok");
Button cancelButton = new
Button("Cancel");
aPanel.add(okButton));
aPanel.add(cancelButton));
Labels
• This class is a Component which displays a single line of text.
• Labels are read-only. That is, the user cannot click on a label to edit
the text it displays.
• Text can be aligned within the label

Constructors
1) Label()
Constructs an empty label.
2)Label(String text)
Constructs a new label with the specified string of text, left justified.
3)Label(String text, int alignment)
Constructs a new label that presents the specified string of text with
the specified alignment.
( LEFT=0, CENTER=1, RIGHT=2 )
Label Ll = new Label(“First Label");
Ll.setAlignment(Label.RIGHT);
L1.setBounds(50,100,30,40);

Label L2 = new Label(“Second Label");


L2.setAlignment(Label.CENTER);
L2.setBounds(100,200,30,40);

Buttondemo.java
List

• This class is a Component which displays a list of Strings.


• The list is scrollable, if necessary.
• Sometimes called Listbox in other languages.
• Lists can be set up to allow single or multiple selections.
• The list will return an array indicating which Strings are
selected
List

Constructors

1) List()
Creates a new scrolling list.
2) List(int rows)
Creates a new scrolling list initialized with the specified
number of visible lines.
3List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified
number of rows.

Listdemo.java
Checkbox
• This class represents a GUI checkbox with a textual label.
• The Checkbox maintains a boolean state indicating whether it is
checked or not.
• If a Checkbox is added to a CheckBoxGroup, it will behave like a
radio button.

Constructors

1) Checkbox()
Creates a check box with an empty string for its label.
2) Checkbox(String label)
Creates a check box with the specified label.
3)Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified
state.
Checkbox
4) Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified
state, and in the specified check box group.

5)Checkbox(String label, CheckboxGroup group, boolean state)


Creates a check box with the specified label, in the specified check
box group, and set to the specified state.

CheckboxGroup cbg=new CheckboxGroup();


Checkbox c1=new Checkbox(“C++”,cbg,false);
Checkbox c2=new Checkbox(“Java”,cbg,true);
f.add(c1);
f.add(c2);

CheckboxGroupExample.java
Choice

• This class represents a dropdown list of Strings.


• Similar to a list in terms of functionality, but displayed
differently.
• Only one item from the list can be selected at one time and the
currently selected element is displayed.

Choice C1 = new Choice();


C1.add(“India");
C1.add(“UK");
C1.add(“USA");

ChoiceExample.java
TextField

• This class displays a single line of optionally editable text.


• This class inherits several methods from TextComponent.
• This is one of the most commonly used Components in the AWT

TextField emailTextField = new TextField();


TextField passwordTextField = new TextField();
passwordTextField.setEchoChar("*");

String userEmail = emailTextField.getText();


String userpassword = passwordTextField.getText();
TextArea

• This class displays multiple lines of optionally editable text.


• This class inherits several methods from TextComponent.
• TextArea also provides the methods: appendText(), insertText()
and replaceText()

// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);

String userFullAddress= fullAddressTextArea.getText();

TextExample.java
Layout Managers

•Since the Component class defines the setSize() and setLocation()


methods, all Components can be sized and positioned with those
methods.
•Problem: the parameters provided to those methods are defined in
terms of pixels. Pixel sizes may be different (depending on the
platform) so the use of those methods tends to produce GUIs
which will not display properly on all platforms.
•Solution: Layout Managers. Layout managers are assigned to
Containers. When a Component is added to a Container, its
Layout Manager is consulted in order to determine the size and
placement of the Component.
Layout Managers (cont)

▪ Every container has a default layout manager, but


we can explicitly set the layout manager as well
▪ Each layout manager has its own particular rules
governing how the components will be arranged
▪ Some layout managers pay attention to a
component's preferred size or alignment, while
others do not
▪ A layout manager attempts to adjust the layout as
components are added and as containers are
resized
Layout Managers (cont)

•There are several different LayoutManagers, each of which sizes


and positions its Components based on an algorithm:
•FlowLayout
•BorderLayout
•GridLayout
•CardLayout
•GridBagLayout

•For Windows and Frames, the default LayoutManager is


BorderLayout. For Panels, the default LayoutManager is
FlowLayout
Flow Layout
• The algorithm used by the FlowLayout is to lay out Components
like words on a page: Left to right, top to bottom.
• It fits as many Components into a given row before moving to the
next row.
• Rows are created as needed to accommodate all of the
components
• Components are displayed in the order they are added to the
container
• Each row of components is centered horizontally in the window
by default, but could also be aligned left or right
• Also, the horizontal and vertical gaps between the components can
be explicitly set
FlowLayout class contains three constants you can
use to align Components

1. FlowLayout.LEFT
2. FlowLayout.CENTER
3. FlowLayout.RIGHT

If you do not specify alignment, Components are


center-aligned in a FlowLayout Container by default
Flow Layout Constructors
1)FlowLayout(align, hgap, vgap)
align – alignment used by the manager
hgap – horizontal gaps between components
vgap – vertical gaps between components
2)FlowLayout(align)
align – alignment used by the manager
A default 5-unit horizontal and vertical gap.

3)FlowLayout()

A centered alignment and a default 5-unit


horizontal and vertical gap.

FlowLayoutDemo.java
Border Layout

• The BorderLayout Manager breaks the Container into 5 regions


(North, South, East, West, and Center).
• When you add a component to a container that uses BorderLayout,
the add() method uses two arguments the component and the region
to which the component is added

Frame aFrame = new Frame();


aFrame.add(new Button("Ok"),BorderLayout.NORTH);
aFrame.add(new Button("Add"), BorderLayout.SOUTH);
aFrame.add (new Button("Delete"), BorderLayout.EAST);
aFrame.add(new Button("Cancel"), BorderLayout.WEST);
Border Layout (cont)

• The regions of the BorderLayout are defined as follows:

North

West Center East

South
Border Layout Constructors

1)BorderLayout(hgap, vgap)
hgap – horizontal gaps between components
vgap – vertical gaps between components

2)BorderLayout()
No vertical or horizontal gaps.

BorderDemo.java
Grid Layout

•The GridLayout class divides the region into a grid of


equally sized rows and columns.
•Components are added left-to-right, top-to-bottom.
•The number of rows and columns is specified in the
constructor for the LayoutManager.
•You cannot skip a position or specify an exact position
for a component
•You can add a blank label to a grid position and give
the illusion of skipping a position
Grid Layout Constructors
1)GridLayout(r, c, hgap, vgap)
r – number of rows in the layout
c – number of columns in the layout
hgap – horizontal gaps between components
vgap – vertical gaps between components
2)GridLayout(r, c)
r – number of rows in the layout
c – number of columns in the layout
No vertical or horizontal gaps.
3)GridLayout()
A single row and no vertical or horizontal gaps.

GridLayoutExample.java
Card Layout

• You can use CardLayout when you want multiple


compnoents to share the same display space
• If multiple containers exist in the application but only one is
to be displayed at a time, you could use CardLayout
• The CardLayout manager generates a stack of containers or
components, one on top of another
• Each component is a ‘card’ and each ‘card’ can be any
component type ex., Button, Label, or Panel
Card Layout Constructors
1.CardLayout(): creates a card layout with zero horizontal
and vertical gap.

2.CardLayout(int hgap, int vgap): creates a card layout


with the given horizontal and vertical gap.

-> The CardLayout class manages two or more components


(usually JPanel instances) that share the same display
space.

-> When using the CardLayout class, the user choose


between the components by using a combo box. Another
way to accomplish the same task is to use a tabbed pane.
CardLayoutJavaExample
GridBag Layout
• The GridBagLayout is one of the most complex and flexible
layout managers
• There is a grid of rows and columns, but the heights and
widths do not have to be the same. Components can take up
multiple cells as well
• GridBagLayout tries to acknowledge the preferred height and
width of the components
• Each component gets added to the grid with a
GridBagConstraints object to set the parameters for the
component
GridBagContraints Object
▪ Constructor of GridbagLayout
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();

GridBagConstraints object has the following properties


1) gridx, gridy
Specify the row and column at the upper left corner of the
component.The leftmost column has address gridx=0 and the top
row has address gridy=0.

2) gridwidth, gridheight
Specify the number of rows or columns in the component’s display
area. These constraints specify the number of cells the component
uses, not the number of pixels it uses. The default value is 1.
GridBagContraints Object

3) Fill

▪ Used when the component’s display area is larger than the


component’s preferred size to determine whether and how to
resize the component.
▪Valid values (defined as GridBagConstraints constants)
include NONE (the default),HORIZONTAL (make the
component wide enough to fill its display area horizontally, but
do not change its height),VERTICAL (make the component tall
enough to fill its display area vertically, but do not change its
width), and BOTH (make the component fill its display area
entirely).
GridBagContraints Object
4)ipadx, ipady
Specifies the internal padding of the component.
It controls padding between the component and the border of its
area.
The width of the component will be at least its minimum width
plus ipadx pixels. Similarly, the height of the component will be
at least the minimum height plus ipady pixels.

5) insets
Specifies the external padding of the component. It controls
padding between the component and neighboring components.
By default, each component has no external padding.
GridBagConstraints Object

6)weightx, weighty

▪Weights are used to determine how to distribute space among


columns(weightx) and among rows(weighty), specified between
0.0 and 1.0
▪Unless you specify at least one non zero value for weightx or
weighty, all the components clump together in the center of their
container. This is because when the weight is 0.0 (default) the
Gridbag layout puts any extra space between its grid of cells and
the edges of the container.
GridBagContraints Object
7)Anchor
▪ Used when the component is smaller than its display area to
determine where to place the component.
▪Valid values (defined as GridBagConstraints constants)
are CENTER (the default) PAGE_START, PAGE_END,
LINE_START, LINE_END, FIRST_LINE_START, FIRST_LIN
E_END, LAST_LINE_END, and LAST_LINE_START.
▪Here is a picture of how these values are interpreted in a container
that has the default, left-to-right component orientation.
FIRST_LINE_START PAGE_START FIRST_LINE_END

LINE_START CENTER LINE_END

LAST_LINE_START PAGE_END LAST_LINE_END


GridBagLayoutExample
What if I don’t want a LayoutManager?

• LayoutManagers have proved to be difficult to deal with.


• The LayoutManager can be removed from a Container by
invoking its setLayout method with a null parameter.

Panel aPanel = new Panel();


aPanel.setLayout(null);
Menubars
❑ Menus are a number of pull-down combo boxes (In Java called as
Choice) placed at single place for easy selection by the user.
❑ To create menus, the java.awt package comes with mainly four
classes – MenuBar, Menu, MenuItem and CheckboxMenuItem.
❑ All these four classes are not AWT components as they are not
subclasses of java.awt.Component class.
❑ They are subclasses of java.awt.MenuComponent.

1) MenuBar: MenuBar holds the menus. MenuBar is added to frame


with setMenuBar() method. Implicitly, the menu bar is added to
the north (top) of the frame. MenuBar cannot be added to other
sides like south and west etc.

2) Menu: Menu holds the menu items. Menu is added to frame


with add() method. A sub-menu can be added to Menu.
Menubars

3) MenuItem: MenuItem displays the actual option user can select.


Menu items are added to menu with method addMenuItem(). A
dull-colored line can be added in between menu items
with addSeparator() method.

4) CheckboxMenuItem: It differs from MenuItem in that it


appears along with a checkbox. The selection can be done with
checkbox selected.

MenuExample.java
Dialog boxes and File Dialog
❑ Dialog boxes are pop-up windows on the screen that appear for a
small time to take either input or display output while a main
application is running.
❑ Dialog boxes are generally used to draw special attention of the
user like displaying warnings.
❑ Dialog box is a top-level window that comes with a border
including a title bar. The dialog box can be made non-resizable
and the default layout manager is BorderLayout.
❑ A dialog box works within a main program. It cannot be created as
a standalone application.
❑ It is a child window and must be connected to a main program or
to a parent window. Frame is a parent window as it can work
independently.
❑ For example, the Find and Replace Dialog box cannot be
obtained without opening MS-Word document. Likewise, File
Deletion Confirmation box cannot appear without deleting a file.
Types of Dialog boxes

Two types of dialog boxes exist


1)Modal
2)Modeless.

-> Modal dialog box does not allow the user to do any activity
without dismissing (closing) it; example is File Deletion
Confirmation dialog box .

-> Modeless dialog box permits the user to do any activity


without closing it; example is Find and Replace dialog box of
MS Word. Java supports both styles of dialog boxes.

->One more dialog box exists with AWT, known as File


dialog which gets the platform dependent file searching dialog
box.
Constructors of Dialog class
1 Dialog(Dialog owner)
Constructs an initially invisible, modeless Dialog with the
specified owner Dialog and an empty title.
2 Dialog(Dialog owner, String title)
Constructs an initially invisible, modeless Dialog with the
specified owner Dialog and title.

3 Dialog(Dialog owner, String title, boolean modal)


Constructs an initially invisible Dialog with the specified
owner Dialog, title, and modality.

4 Dialog(Dialog owner, String title, boolean modal,


GraphicsConfiguration gc)
Constructs an initially invisible Dialog with the specified
owner Dialog, title, modality and GraphicsConfiguration.

DialogExample

You might also like