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

Lecture 19 AWT

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 19 AWT

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Maharaja Agrasen Institute of Technology

CIC-212 Java Programming

AWT (Abstract Windowing Toolkit)


Objectives

The objectives of this chapter are:


To discuss the classes present in the java.awt package
To understand the inheritance hierarchy of the AWT
To outline the basic structure of GUIs
To show how to add components to containers
To understand how to use Layout Managers
To understand basic graphics processing under the AWT
AWT (Abstract Windowing Toolkit)

The AWT is roughly broken into three categories


Components
Layout Managers
Graphics

Many AWT components have been replaced by Swing


components
It is generally not considered a good idea to mix Swing
components and AWT components. Choose to use
one or the other.
AWT Class Hierarchy

Component

Container Window Frame

Button Panel
List

Checkbox

Choice Note: There are more classes, however,


these are what are covered in this chapter
Label

TextComponent TextField

TextArea
Component

Component is the superclass of most of the displayable


classes defined within the AWT. Note: it is abstract.
MenuComponent is another class which is similar to
Component except it is the superclass for all GUI items
which can be displayed within a drop-down menu.
The Component class defines data and methods which
are relevant to all Components
setBounds
setSize
setLocation
setFont
setEnabled
setVisible
setForeground -- colour
setBackground -- colour
Container

Container is a subclass of Component. (ie. All containers


are themselves, Components)
Containers contain components
For a component to be placed on the screen, it must be
placed within a Container
The Container class defined all the data and methods
necessary for managing groups of Components
add
getComponent
getMaximumSize
getMinimumSize
getPreferredSize
remove
removeAll
Windows and Frames

The Window class defines a top-level Window with no


Borders or Menu bar.
Usually used for application splash screens
• Frame defines a top-level Window with Borders and a
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);
Panels
When writing a GUI application, the GUI portion can
become quite complex.
To manage the complexity, GUIs are broken down into
groups of components. Each group generally provides a
unit of functionality.
A Panel is a rectangular Container whose sole purpose is to
hold and manage components within a GUI.

Panel aPanel = new Panel();


aPanel.add(new Button("Ok"));
aPanel.add(new Button("Cancel"));

Frame aFrame = new Frame("Button Test");


aFrame.setSize(100,100);
aFrame.setLocation(10,10);

aFrame.add(aPanel);
Buttons
This class represents a push-button which displays some
specified text.
When a button is pressed, it notifies its Listeners. (More
about Listeners in the next chapter).
To be a Listener for a button, an object must implement the
ActionListener Interface.

Panel aPanel = new Panel();


Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");

aPanel.add(okButton));
aPanel.add(cancelButton));

okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
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

Label aLabel = new Label("Enter password:");


aLabel.setAlignment(Label.RIGHT);

aPanel.add(aLabel);
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 aList = new List();
aList.add("Calgary");
aList.add("Edmonton");
aList.add("Regina");
aList.add("Vancouver");
aList.setMultipleMode(true);
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.

Checkbox creamCheckbox = new CheckBox("Cream");


Checkbox sugarCheckbox = new CheckBox("Sugar");
[ ]
if (creamCheckbox.getState())
{
coffee.addCream();
}
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 aChoice = new Choice();


aChoice.add("Calgary");
aChoice.add("Edmonton");
aChoice.add("Alert Bay");
[ ]

String selectedDestination= aChoice.getSelectedItem();


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


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.
NOTE: If you use a Layout Manager, you can no longer
change the size and location of a Component through the
setSize and setLocation methods.
Layout Managers (cont)

There are several different LayoutManagers, each of which


sizes and positions its Components based on an algorithm:
FlowLayout
BorderLayout
GridLayout

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.

Panel aPanel = new Panel();


aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Border Layout

The BorderLayout Manager breaks the Container up into 5


regions (North, South, East, West, and Center).
When Components are added, their region is also
specified:

Frame aFrame = new Frame();


aFrame.add("North", new Button("Ok"));
aFrame.add("South", new Button("Add"));
aFrame.add("East", new Button("Delete"));
aFrame.add("West", new Button("Cancel"));
aFrame.add("Center", new Button("Recalculate"));
Border Layout (cont)

The regions of the BorderLayout are defined as follows:

North

West Center East

South
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.

Panel aPanel = new Panel();


GridLayout theLayout = new GridLayout(2,2);
aPanel.setLayout(theLayout);

aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
What if I don’t want a LayoutManager?

LayoutManagers have proved to be difficult and frustrating


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

Ch. VIII - 22
Graphics

It is possible to draw lines and various shapes within a


Panel under the AWT.
Each Component contains a Graphics object which defines
a Graphics Context which can be obtained by a call to
getGraphics().
Common methods used in Graphics include:
• drawLine • fillOval
• drawOval • fillPolygon
• drawPolygon • fillRect
• drawPolyLine • fillRoundRect
• drawRect • setColor
• drawRoundRect • setFont
• drawString • setPaintMode
• draw3DRect • drawImage
• fill3DRect
• fillArc
Frame
import java.awt.*;

public class TestFrame extends Frame {


public TestFrame(String title){
super(title);
}
public static void main(String[] args){
Frame f = new
TestFrame("TestFrame");
f.setSize(400,400);
f.setLocation(100,100);
f.show();
}}
UNIT-III Abstract Window Toolkit
How to Use Buttons?
public class TestButton extends
Frame {
public TestButton(String title)
{
super(title);
Button hw = new
Button("Hello World!");
add(hw);
}
….
}

UNIT-III Abstract Window Toolkit


ButtonTest.java
// Displays a frame containing a single button.
// WARNING: Frame cannot be closed.
import java.awt.*;
// Driver class
public class ButtonTest {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);
}
}
// Frame class
class ButtonTestFrame extends Frame {
public ButtonTestFrame(String title) {
super(title);
setLayout(new FlowLayout());
Button b = new Button("Testing");
add(b);
Adding Components to a Frame
 Frame created by the ButtonTest
program:

 Pressing the “Testing” button has no effect.


Adding Components to a Frame
 Instead of calling setSize, the main method in
ButtonTest could have called pack:
f.pack();
 pack makes the frame just large enough to display
the components within it:

 Regardless of whether setSize or pack is


called, the user can manually resize the frame.
UNIT-III Abstract Window Toolkit
Adding Components to a Frame
 It’s not necessary to have two separate
classes, (ButtonTest and
ButtonTestFrame).
 By moving the main method from
ButtonTest to
ButtonTestFrame, the program
could be condensed to one class
(ButtonTestFrame).
How to Use Labels?
public class TestLabel extends Frame {
public TestLabel(String title){
super(title);
Label label1 = new Label();
label1.setText("Label1");
Label label2 = new Label("Label2");
label2.setAlignment(Label.CENTER);
Label label3 = new Label("Label3");

add(label1,"North");
add(label2,"Center");
add(label3,"South");
}
}
How to Use Checkboxes?
public class TestCheckbox extends Frame {
public TestCheckbox(String title){
super(title);

CheckboxGroup cbg = new CheckboxGroup();


Checkbox cb1 = new Checkbox("American Express",cbg,false);
Checkbox cb2 = new Checkbox("Visa",cbg,false);
Checkbox cb3 = new Checkbox("Mastercard",cbg,true);
add(cb1,"North");
add(cb2,"Center");
add(cb3,"South");
}

}
How to Use Choices?
public class TestChoice extends Frame {
public TestChoice(String title){
super(title);

Choice choice = new Choice();


choice.add("ichi");
choice.add("ni");
choice.add("san");
add(choice);
}
How to Use TextField &
TextArea
public class TestText extends Frame {
public TestText(String title){
super(title);

TextField textField = new TextField(20);


TextArea textArea = new TextArea(5,
20);

textArea.setEditable(false);
textField.setText("TextField");
textArea.setText("TextArea Line1 \n TextArea
Line2");

add(textField,"North");
add(textArea,"South");
}

UNIT-III } Abstract Window Toolkit
How to Use Lists?
public class TestList extends Frame {
public TestList(String title){
super(title);
List l = new List(2, true); //prefer 2 items visible
l.add("zero");
l.add("uno");
l.add("dos");
l.add("tres");
l.add("cuatro");
l.add("cinco");
l.add("seis");
l.add("siete");
l.add("ocho");
l.add("nueve");
add(l);
How to Use Menus?
public class TestMenu extends Frame {
public TestMenu(String title){
super(title);

MenuBar mb = new
MenuBar();
setMenuBar(mb);

Menu m1 = new
Menu("Menu 1");
mb.add(m1);
MenuItem mi1_1 = new
MenuItem("Menu Item
1_1"); m1.add(mi1_1);
m1.addSeparator();
MenuItem mi1_2 = new
MenuItem("Menu Item
1_2"); m1.add(mi1_2);

Menu m2 = new
How to Use Canvases and
Graphics Primitives?
 For drawing geometric shapes, texts, and
images
 An abstract class
– the extended class must override paint()
Line Oval

RoundRectangle
Rectangle

Polygon Arc
drawLine(x1,y1,x2,y2)
class MyCanvas extends Canvas {
public void paint(Graphics g)
{ g.setColor(Color.blue);
int x1 = 161,
y1 = 186,
(x1,y1)

x2 y2
= 181, (x2,y2)
= 206;

g.drawLine(x1,y1,x2,y2);
}
fillOval(x,y,w,h)
drawOval(x,y,w,h)
g.setColor(Color.blue);
{
int x = 239,
y = 186,
w = 48,
h = 32;
g.fillOval(x,
y,w,h);
}

UNIT-III Abstract Window Toolkit


fillPolygon(int[] xs, int[] ys)
drawPolygon(int[] xs, int[] ys)
g.setColor(Color.green);
{
int xs[] = {161,161,185,209,185,161};
int ys[] = {310,334,358,334,310,310};
g.fillPolygon(xs,ys,6);
}
fillRect(x,y,w,h)
drawRect(x,y,w,h)
g.setColor(Color.pink);
{
int x = 239,
y = 248,
w = 48,
h = 32;
g.fillRect(x,y,
w,h);
}
fillRoundRect(x,y,w,h,rw,rh)
drawRoundRect(x,y,w,h,rw,rh)
g.setColor(Color.yellow);
{
int x = 161,
y = 248,
w = 48,
h = 32, roundW
= 25, roundH
= 25;
g.fillRoundRect(x,
y,w,h,roundW,r
oundH);
}
fillArc(x,y,w,h,sa,a)
drawArc(x,y,w,h,sa,a)
g.setColor(Color.orange);
{
int x = 239,
y = 310,
w = 48,
h = 48, startAngle
= 20, angle =
90;
g.fillArc(x,y,w,h,star
tAngle,angle);
}
drawString(s,x,y)
FontMetrics

(x,y)
drawString, Font, & FontMetrics
class MyCanvas extends Canvas {

public void paint(Graphics g)


{ g.setFont(new
Font("Dialog",0,20)); FontMetrics fm
= g.getFontMetrics(); int x = 100;
int y = 100;
g.drawString("Hello",x,y);
y = y+fm.getHeight();
g.drawString("World",x,y);
}
}
drawImage(image,x,y,w,h,ob)
Image im = Toolkit.getDefaultToolkit().getImage(name);

g.drawImage(im, x, y, w, h, observer);
drawImage
public class TestImage extends Frame {
Image im;

public TestImage(String title){


super(title);
im = Toolkit.getDefaultToolkit().getImage("jp2.jpg");
if (im==null)
{ System.out.println("No
image"); System.exit(0);
}
}
public void paint(Graphics g){
g.drawImage(im,0,0,im.getHeight(thi
s),im.getWidth(this),this);
…}
Layout of Components
 BorderLayout  GridLayout
– north, south, west, east – tabular form (rows &
& center columns)
 FlowLayout 
GridBagLayout
– left to right & top – tabular form(variable
down row heights and
 CardLayout column widths)

– stack of panels
Use Layout Managers
setLayout(new BorderLayout());
setLayout(new CardLayout(());
setLayout(new FlowLayout());
setLayout(new
GridLayout(rows,columns,xgap,
ygap));
 Default layout managers
– Windows (Frames &
Dialogs)
• BorderLayout
UNIT-III Abstract Window Toolkit
– Panels (Applets)
How to Use BorderLayout?
import java.awt.*;
public class TestBorderLayout {
public static void main(String[] args){
Frame f = new Frame("TestBorderLayout");
f.setSize(200,200);
f.add("North", new Button("North"));
f.add("South", new Button("South"));
f.add("East", new Button("East"));
f.add("West", new Button("West"));
f.add("Center", new Button("Center"));
f.setVisible(true);
}
}
How to Use FlowLayout?
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args)
{ Frame f = new
Frame("TestFlowLayout");
f.setSize(200,200);
f.setLayout(new FlowLayout());
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new Button("Button 5"));
f.setVisible(true);
}
How to Use CardLayout?
import java.awt.*;

public class TestCardLayout {


public static void main(String[] args)
{ Frame f = new Frame("TestCard
Layout"); f.setSize(200,200);
f.setLayout(new CardLayout());
f.add("GraphicsPanel",new GraphicsPanel());
f.add("LabelPanel",new LabelPanel());
f.add("ButtonPanel",new ButtonPanel());

f.setVisible(true);
}
How to Use GridLayout?
import java.awt.*;
public class TestGridLayout {
public static void main(String[] args)
{ Frame f = new
Frame("TestGridLayout");
f.setSize(200,200);
f.setLayout(new GridLayout(2,3));
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new Button("Button 5"));
f.setVisible(true);
}

You might also like