Professional Documents
Culture Documents
In java GUI can be design using some predefined classes. All these
classes are defined in java.awt package.
java.awt class
The AWT provides nine basic non-container component and three container
classes.
AWT Classes
• The AWT classes are contained in the java.awt package.
• It is one of Java’s largest packages.Fortunately, because it is logically organized
in a top-down, hierarchical fashion,
Component
At the top of the AWT hierarchy is the Component class.
• Other Container objects can be stored inside of a Container (since they are
themselves instances of Component).
Frame
• Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.
Canvas
• Although it is not part of the hierarchy for applet or frame windows, there is one other
type of window that you will find valuable: Canvas. Derived from Component,
• Canvas encapsulates a blank window upon which you can draw.
Container class
Window The window is the container that have no borders and menu bars.
- You must use frame, dialog or another window for creating a window.
Frame - The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, text field etc.
Panel - The Panel is the container that doesn't contain title bar and menu
bars. It can have other components like button, text field and etc.
Before adding the components that make up a user interface, the programmer must
create a container.
Creating Frame
Create a subclass of Frame
Once you have defined a Frame subclass,you can create an object of that
class.But it will note be initially visible When created,the window is given a
default height and width
You can set the size of the window explicitly by calling the following
method
void setSize(int height,int width);
void setSize(dimension d);
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
MyWindowAdapter adapter = new MyWindowAdapter(this);
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 40, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sf;
public MyWindowAdapter(SampleFrame sf) {
this.sf = sf;
}
Frame example (cont.,)
public void windowClosing(WindowEvent we) {
sf.setVisible(false);
}
}
public class testFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A
Frame Window");
f.setSize(500, 500);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
OUTPUT
EVENT HANDLING
EVENT HANDLING (Cont)
HOW TO USE EVENTS
Identify which events you wish to listen for (some components generate
more than one type of event)
ActionEvent - ActionListener
AdjustmentEvent - AdjustmentListener
- ComponentListener
ComponentEvent - ContainerListener
ContainerEvent - FocusListener
FocusEvent - ItemListener
ItemEvent - KeyListener
KeyEvent - MouseListener
MouseEvent - MouseMotionListener
TextEvent - TextListener
WindowEvent - WindowListener
ActionEvent
First declare an event handler class and specify that the class either
implements an ActionListener interface or extends a class that implements
an ActionListener interface.
For example
public class MyClass implements ActionListener
{
//abstract methods of ActionListener inteface
}
ActionEvent Listener (cont)
On entering the character from any source generates the key event.This
interface has 3 methods. These are
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Key extends Applet implements KeyListener {
int X=20,
Y=30;
String msg="KeyEvents--->";
public void init() {
addKeyListener(this);
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k) {
showStatus("KeyDown");
int key=k.getKeyCode();
Key Event example
switch(key) {
case KeyEvent.VK_UP: //constant for non-numpad up arrow key
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN: //constant for non-numpad down arrow key
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT: //constant for non-numpad left arrow key
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT: //constant for non-numpad right arrow key
showStatus("Move to Right");
break;
}
repaint();
}
Key Event example
Called just after the user presses a mouse button while the cursor is over
the listened-to component.
Called just after the user releases a mouse button after a mouse press
over the listened-to component
Called just after the cursor enters the bounds of the listened-to component.
Called just after the cursor exits the bounds of the listened-to component.
MouseMotionEvent
focusGained:
Called just after the listened-to component gets the
focus.
focusLost:
Called just after the listened-to component Loses the focus.
Example
import java.awt.*;
import java.awt.event.*;
public class FocusListenertest extends Frame
implements FocusListener
{
//initialization occur…
public FocusListenertest()
{
Label l;
add(b1=new Button ("First"),"South");
add(b2=new Button ("Second"),"North");
add(l);
b1.addFocusListener(this)
;
b2.addFocusListener(this)
; setSize(200,200);
Example
}
public void focusGained(FocusEvent fe) {
if(fe.getSource()==b1)
{
l.setText("focus gained of first & Lost of second");
}
public void focusLost(FocusEvent fe) {
if(fe.getSource()==b1)
{
l.setText("focus Lost of First & Gained of Second ");
}
OUTPUT
OUTPUT
WindowEvent Listener
windowOpened:
Called just after the listened-to window has been shown for
the first time.
windowClosing:
Called in response to a user request for the listened-to
window to be closed.To actually close the window ,the listener
should invoke the windowsdispose or setVisible(fasle) method.
windowClosed:
Called just after the listened-to window has closed.
windowIconified:
Called just after the listened-to window is iconified .
windowDeicoified:
Called just after the listened-to window is deiconified.
WindowEvent Class
itemStateChanged:
Example
• //where initialization occurs checkbox.addItemListener(this); ...
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{ label.setVisible(true); ... }
else
{ label.setVisible(false);
}}
GRAPHICS PROGRAMMING
40
(100, 40)
Y
DRAWING SHAPES
A shape can be filled or unfilled, depending on which
method is invoked
The method parameters specify coordinates and
sizes
Shapes with curves, like an oval, are usually drawn by
specifying the shape’s bounding rectangle
An arc can be thought of as a section of an oval
DRAWING A
LINE
10 150 X
20
45
20
40
100
20
80
bounding
rectangl
Y e 50
20
80
bounding
rectangl
Y e 50
Class Constructor
Color.black 0, 0, 0
Color.blue 0, 0, 255
Color.cyan 0, 255, 255
Color.orange 255, 200, 0
Color.white 255, 255, 255
255, 255, 0
Color.yellow
THE COLOR CLASS
METHODS
Method name Meaning
getBlue() gets the blue component
getGreen() gets the green component
getRed() gets the red component
getColor(String) Gets the specified color property
getColor(int) Gets the specified color property of the
color value
getRGB() Gets the RGB value representing the
color in the default RGB color model
FONTS
The AWT supports multiple type fonts.fonts have family
name,a logical font name, and a face name.
Fonts are encapsulated by the Font class.
Font(String name,int fontStyle,int size);
Variable Meaning
g.drawString(“Hello World”,60,40);
OUTPUT
AWT
CONTROLS
AWT Supports the following types of controls.
Label List
Choice list
To add controls you must create an window and add by following method.
Component .add(ComponentObj);
void remove(ComponentObj);
LABEL
A label displays a single line of read only text ,the label
cannot changed by the end user anyway.
Creating the Label
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListene
r(this);
cancelButton.addActionList
ener(this);
Lis
t
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);
Checkbo
x
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.
String selectedDestination=
aChoice.getSelectedItem();
Text
Field
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
// 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
North
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.
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new
MENU BAR AND
MENU
A menu bar displays a list of top-level menu choices
Each choice is associated with a drop-down menu
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
PROGRAM
(CONT.)
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g)
{ g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10,
240);
}
}
PROGRAM
(CONT.)
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
PROGRAM
(CONT.)
// Handle action events
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = (String)ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
PROGRAM
(CONT.)
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
PROGRAM
(CONT.)
// Handle item events
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
PROGRAM
(CONT.)
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
Sam
ple
out
put
is
sho
wn
her
e