Post on 05-Apr-2018
transcript
8/2/2019 AWT by Kamalakar Dandu
1/70
Java Graphics Programming
8/2/2019 AWT by Kamalakar Dandu
2/70
Using AWT Components
Figure shows the inheritance hierarchies for
all the AWT component classes.
8/2/2019 AWT by Kamalakar Dandu
3/70
The AWT
Provides basic GUI components which areused in all Java applets and applications
Has super classes which can be extendedand their properties inherited; classes can
also be abstract Ensures that every GUI component that isdisplayed on the screen is a subclass of theabstract class Component
Contains Container which is an abstractsubclass of Component and which includestwo subclasses
Panel
Window
8/2/2019 AWT by Kamalakar Dandu
4/70
Containers
The two main types of containers are Windowand Panel.
Windows are objects ofjava.awt.Window.
Panels are objects of java.awt.Panel.
8/2/2019 AWT by Kamalakar Dandu
5/70
Building Graphical User
Interfaces
The position and size of a component in a container
is determined by a layout manager. You can control the size or position of components
by disabling the layout manager.
You must Then use setLocation(),
setSize(), or setBounds() on components tolocate them in the container.
8/2/2019 AWT by Kamalakar Dandu
6/70
Frames
Are subclasses of Window
Have title and resize corners
Inherit from Component and add components withthe addmethod
Can be used to create invisible Frame objectswith a title specified by String
Have Border Layout as the default layoutManager
Use the setLayout method to change the
default layout manager
8/2/2019 AWT by Kamalakar Dandu
7/70
Panels
Provide a space for components
Allow subpanels to have their own layout
manager Add components with the add method
8/2/2019 AWT by Kamalakar Dandu
8/70
Container Layouts
Flow Layout - Default layout for a Paneland Applet.
Border Layout - Default layout for aFrame
Grid Layout
Card Layout
GridBag Layout
8/2/2019 AWT by Kamalakar Dandu
9/70
The Frame class provides windows for applets and applications.
Every GUI application needs at least one Frame.
How to use Frames :
8/2/2019 AWT by Kamalakar Dandu
10/70
How to use Frames :
Import java.awt.*;
public class MyWindow extends Frame {
MyWindow() {
setTitle(Employee Registration Form);
setSize(200,200);
setVisible(true);
}
public static void main(String[] ar) {
MyWindow mw = new MyWindow();
}
}
8/2/2019 AWT by Kamalakar Dandu
11/70
Here's an example of using a Panel instance to hold someComponents:
Panel p1 = new Panel();
p1.add(new Button(Submit"));
p1.add(new Button(Reset"));p1.add(new Button(Cancel"));
add(North,p1);//adding to North
// side of the Frame
How to use Panels:
8/2/2019 AWT by Kamalakar Dandu
12/70
The Button class provides a default button implementation.A button is a simple control that generates an action event
when the user clicks it.
//In initialization code:
Buttonb1 = new Button();
b1.setLabel(Click Me");
How to use Buttons :
8/2/2019 AWT by Kamalakar Dandu
13/70
TheLabel class provides an easy way of putting unselectable
text in your program's GUI.
Labels are aligned to the left of their drawing area, by default.
You can specify that they be centered or right-aligned by
specifying Label.CENTER or Label.RIGHT either to the Label
constructor or to the setAlignment() method. As with
every Component, you can also specify the font and color of a
Label.
How to use Labels :
8/2/2019 AWT by Kamalakar Dandu
14/70
Below is the code that the applet uses to create its labels and
set their alignment.
How to use Labels :
Label label1 = new Label();
label1.setText("Left");
Label label2 = new Label("Center");
label2.setAlignment(Label.CENTER);Label label3 = new Label("Right", Label.RIGHT);
Besides the constructor, setText(), andgetAlignment() methods
used above, the Label class also provides getText() andgetAlignment() methods.
8/2/2019 AWT by Kamalakar Dandu
15/70
How to use Text Fields :
import java.awt.*;
class TextDemo extends Frame {
TextField tf1, tf2;
TextDemo() {
setLayout(new FlowLayout());
setSize(300, 200);
tf1 = new TextField();tf2 = new TextField();
add(tf1);
add(tf2);
}public static void main(String args[]) {
TextDemo window = new TextDemo();
window.show();
}
}
8/2/2019 AWT by Kamalakar Dandu
16/70
Lab Session
Write a program to create a Frame. Create two panels, one
with two buttonsOk and Cancel, using FlowLayout,
and another panel with two text fields one below the other,
using BorderLayout.
Place one panel to the north and one to the south of the
Frame
Write a program to place six text fields in 2 rows by 3
columns fashion.
8/2/2019 AWT by Kamalakar Dandu
17/70
Event Driven Programming
8/2/2019 AWT by Kamalakar Dandu
18/70
What Is An Event?
Events - Objects that describe what happened
Event source - The generator of an event Event handlers - A method that receives an
event
object,deciphers it,and processes the usersinteraction
8/2/2019 AWT by Kamalakar Dandu
19/70
Delegation Model (JDK 1.1
and Beyond )
Events are not accidentally handled.
There is better distribution of work amongthe classes.
8/2/2019 AWT by Kamalakar Dandu
20/70
GraphicsThe Color class
Color(int red, int green, int blue) or Color.blue value
setForeground(Color.blue) or setBackground(Color.blue)
The Font class
Font(String name, int style, int size)
Styles - Font.PLAIN, Font.BOLD, Font.ITALIC
can have Font.BOLD | Font.ITALIC also
The FontMetrics class FontMetrics(Font f)
The Graphics class -Every component has a graphics context
Component.getGraphics() - Ex. button.getGraphics();
g.getFontMetrics()
8/2/2019 AWT by Kamalakar Dandu
21/70
Lab Session
Write a program to display the name of your company with a
font size of 30, color - black and background - gray in a
frame.
Write a program to display all possible shapes available in
the graphics class, in a frame using the API.
8/2/2019 AWT by Kamalakar Dandu
22/70
Creating User Interfaces
8/2/2019 AWT by Kamalakar Dandu
23/70
Checkbox
CheckboxGroup
Choice Dialog
List
Menu
TextArea
List of AWT Components
8/2/2019 AWT by Kamalakar Dandu
24/70
The Checkbox class provides checkboxes :-
Two-state buttons that can be either "on" or "off".
When the user clicks a checkbox, the checkbox state
changes and generates an event.
If you want a group of checkboxes in which only one
checkbox at a time can be "on", you can add a
CheckboxGroup (You might know this UI element as aradio button.)
How to use Checkboxes :
8/2/2019 AWT by Kamalakar Dandu
25/70
Checkbox cb1, cb2, cb3;//These are independent checkboxes.
cb1 = new Checkbox();//Default state is "off" (false).
cb1.setLabel(Java");
cb2 = new Checkbox(Cobol");
cb3 = new Checkbox(Visual Basic");
cb3.setState(true);//Set state to "on" (true).. . .
How to use Checkboxes :
H t Ch i
8/2/2019 AWT by Kamalakar Dandu
26/70
A Choice is a Drop Down Menu When the user chooses an item,
the Choice generates an event.
Choices are useful when you need to display a number of
alternatives in a limited amount of space
How to use Choice :
8/2/2019 AWT by Kamalakar Dandu
27/70
Choice choice; //Drop Down list of choices
//...Where initialization occurs:
choice = new Choice();choice.addItem(Java");
choice.addItem(Oracle");
choice.addItem(Visual Basic);
choice.addItem(SmallTalk");
How to use Choice :
8/2/2019 AWT by Kamalakar Dandu
28/70
How to use Dialogs :
Windows that are dependent on other windows -- with the Dialog
class. - new Dialog(frame), where frame is the parent window.
We can create a dialog with a model using a different constructor.
By default, dialogs are non-modal -- the user can keep them up
and still work in other windows of the application
How to use Dialogs
8/2/2019 AWT by Kamalakar Dandu
29/70
How to use Dialogs :
Here's just the code that implements the Dialog object:
public class MyWindow extends Frame {Dialog d;
Label l;
MyWindow() {
d=new Dialog(this,true);
l=new Label(Invalid number entered);
d.add(Center,l);
d.setSize(100,200); //This is a must
d.show(); //To show the dialog window.
// We can activate a dialog window based on
// an event.
}
}
8/2/2019 AWT by Kamalakar Dandu
30/70
TheListclass provides a scrollable area containing selectable text
items (one per line).
Lists can allow either multiple selections or just one selection at a
time.
How to use Lists :
8/2/2019 AWT by Kamalakar Dandu
31/70
//Build first list, which allows multiple selections.
List1 = new List(2, true);//prefer 2 items visible
List1.add(Unix");
List1.add(Dos");
//Build second list, which allows one selection at a time.
List2 = new List();//Defaults to none visible, only one selectableList2.add(Unix");
List2.add(Dos");
How to use Lists :
8/2/2019 AWT by Kamalakar Dandu
32/70
How to use Menus:
Menu classes inherit from theMenuComponent class :
The AWT provides the following MenuComponent subclasses tosupport menus:
MenuBar :
MenuBar represents the platform-dependent notion of agroup of menus attached to a window. MenuBars can notbe
bound to Panels.
Menu :Each menu is represented by a Menu object.
MenuItem :
Each item in a menu is represented by a MenuItem object.
8/2/2019 AWT by Kamalakar Dandu
33/70
How to use Menus:
.Here's just the code that deals with menus:
public class MenuWindow extends Frame {public MenuWindow() {
MenuBar mb;
Menu file, edit;
MenuItem newfile, open, close;MenuItem cut, copy, paste;
//Build the menu bar.
mb = new MenuBar();
setMenuBar(mb);//Set menu bar for the frame
Contd. In Next Page...
How to use Menus:
8/2/2019 AWT by Kamalakar Dandu
34/70
file= new Menu(File);
mb.add(file);
newfile = new MenuItem(New"); file.add(newfile);
open = new MenuItem(Open"); file.add(open);close = new MenuItem(Close"); file.add(close);
How to use Menus:
8/2/2019 AWT by Kamalakar Dandu
35/70
TextArea textArea;
//create text area of 5 rows and 30
//columnstextArea=new TextArea(5,30)
textArea.setEditable(false);
How to use TextArea :
8/2/2019 AWT by Kamalakar Dandu
36/70
Lab Session
Write a program to show the appearance of a Notepad program
using all the menu options.
Create a GUI form using all the GUI components covered in
this session.
Write a program to display a Dialog box with a message, usinga Font and a Color class.
8/2/2019 AWT by Kamalakar Dandu
37/70
Using Listener Interfaces
Component
Button
Listener
ActionListener
actionPerformed(ActionEvent e) {
}
Event Object
ActionEvent
8/2/2019 AWT by Kamalakar Dandu
38/70
List of Listeners
Listener Interfaces Methods
ActionListener void actionPerformed(ActionEvent)
AdjustmentListener adjustmentValueChanged(AdjustmentEvent)
AWTEventListener eventDispatched(AWTEvent)
ComponentListener componentHidden(ComponentEvent)componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
ContainerListener componentAdded(ContainerEvent)componentRemoved(ContainerEvent)
FocusListener focusGained(FocusEvent)
focusLost(FocusEvent)
ItemListener itemStateChanged(ItemEvent)
8/2/2019 AWT by Kamalakar Dandu
39/70
Listener Interfaces Methods
KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseListener mouseClicked(MouseEvent)
mouseEntered(MouseEvent)mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
TextListener textValueChanged(TextEvent)
8/2/2019 AWT by Kamalakar Dandu
40/70
Listener Interfaces Methods
WindowListener windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
8/2/2019 AWT by Kamalakar Dandu
41/70
Event Component
ActionEvent Button, List (Double click), Menu
ItemEvent Check box, List, ChoiceKeyEvent Keyboard
MouseEvent Mouse operations
TextEvent TextField and TextArea.
WindowEvent Window, Frame, Dialog
8/2/2019 AWT by Kamalakar Dandu
42/70
Multiple Listeners
One component can register itself for more thanone listener.
All registered listeners have their handler called
when the event occurs.
8/2/2019 AWT by Kamalakar Dandu
43/70
Lab Session
Write a program to show the event handling of a list, choice,
check box and radio buttons. Show proper messages.
Write a program to change the background color of the frameusing a list of colors.
Create a form with three text fields for Name, Age and Salary.
Show the details on the screen as a single line, when clicked
on the Submit button. Clear the form for next entry.
8/2/2019 AWT by Kamalakar Dandu
44/70
Applets
8/2/2019 AWT by Kamalakar Dandu
45/70
What is an Applet ?
A Java class that can be embedded within an HTML
page and is downloaded and executed by a web browser.
Is loaded as follows :
Browser loads URL
Browser loads the HTML document
Browser loads applet classes
Browser runs the applet
8/2/2019 AWT by Kamalakar Dandu
46/70
Applet Security Restrictions
Most browsers prevent the following
Runtime execution of another program
Any file I/O (input/output)
Calls to any native methods
Attempts to open a socket to any system except the
host that provided the applet.
8/2/2019 AWT by Kamalakar Dandu
47/70
Key Applet Methods
init()
start()
stop()
destroy()
paint()
8/2/2019 AWT by Kamalakar Dandu
48/70
Applet DisplayApplets are graphical in nature
paint() method is called by the browser environment
Example of an applet that uses a paint() method :
import java.awt.*;import java.applet.*;
public class HelloJava extends Applet {
public void paint(Graphics g) {
g.drawString(Hello Java!,25,25);
}
}
8/2/2019 AWT by Kamalakar Dandu
49/70
Applet methods and the Applet LifeCycle
init()
Called when the applet is created
Can be used to initialize data values
start()
Runs when the applet becomes visible
stop()
Called when the applet becomes invisible
destroy()
Called when the browser or the appletviewer is closed
paint()
Called automatically when the applet is started
8/2/2019 AWT by Kamalakar Dandu
50/70
AWT Painting
paint(Graphics g)
repaint()
update(Graphics g)
8/2/2019 AWT by Kamalakar Dandu
51/70
AWT thread (waiting)
update()
update background
call paint()
paint()
Exposurerepaint()
8/2/2019 AWT by Kamalakar Dandu
52/70
What is the appletviewer ?
A Java application that enables you to run applets without
using a web browser
It loads the HTML file supplied as an argument appletviewer HelloJava.html
It needs at least the following HTML code :
8/2/2019 AWT by Kamalakar Dandu
53/70
Syntax of applet tag
[ ]
[ ]
8/2/2019 AWT by Kamalakar Dandu
54/70
Additional Applet Facilities
getDocumentBase() - Returns a URL object that describes
directory of the current browser page.
getCodeBase() - Returns a URL object that describes the
source directory of the applet class.
getImage(URLbase, Stringtarget) and
getAudioClip(URLbase, Stringtarget) - Use the URL
object as a starting point.
8/2/2019 AWT by Kamalakar Dandu
55/70
A sample image test
//HelloJava extended to draw an image
//Assume existence of javalogo.gif
import java.awt.*;
import java.applet.*;
public class HwImage extends Applet {
Image logo;
public void init() {
logo = getImage(getDocumentBase(),
javalogo.gif);}
public void paint(Graphics g) {
g.drawImage(logo,25,25,this);
}
}
8/2/2019 AWT by Kamalakar Dandu
56/70
Looping an Audio Clip
Loading an audio clip
Playing an audio clip
Stopping an audio clip
8/2/2019 AWT by Kamalakar Dandu
57/70
A sample Audio Looping Test
//HelloJava extended to loop an audio track
//Assume existence of spacemusic.auimport java.awt.Graphics;
import java.applet.*;
public class HwLoop extends Applet {
AudioClip sound;
public void init() {sound=getAudioClip(getDocumentBase(),
spacemusic.au);
}
public void paint(Graphics g) {g.drawString(Audio test,25,25);
}
public void start() { sound.loop(); }
public void stop() { sound.stop(); }
}
8/2/2019 AWT by Kamalakar Dandu
58/70
Lab Session
Write a program that demonstrates the use of the life cycle
methods of an applet. Show proper messages on the screen.
Write an applet to load an image file
Write an applet to accept two numbers in text fields and
compute the sum of the numbers when clicked on the Addbutton.
8/2/2019 AWT by Kamalakar Dandu
59/70
Advanced Graphics
8/2/2019 AWT by Kamalakar Dandu
60/70
Grid Bag Layout Manager
GridBagLayout enables finer control over the size and
placement of individual cells in a grid layout. Each
grid area or component is associated with a particular
GridBagConstraints instance that specifies how the
component is laid out within the display area.
Like GridLayout, the GridBagLayout layout manager
aligns components within a rectangular grid of cells.
Where GridLayout and GridBagLayout differ is in
that GridBagLayout use an object called
GridBagConstraints.
8/2/2019 AWT by Kamalakar Dandu
61/70
By setting values within the GridBagConstraints object,
components can be aligned vertically or horizontally (with or
without insets and padding), told to expand to fill the given area
, and instructed on how to behave upon resizing of the window.
You initialize and utilize a GridBagLaoyout and its associated
GriBagConstraints object as follows:private GridBagLayout guiLayout;
private GridBagConstraints guiConstraints;
guiLayout = new GridBagLayout();setLayout(guiLayout);
guiConstraints = new GridBagConstraints();
guiConstraints.anchor = GridBagConstraints.CENTER;
8/2/2019 AWT by Kamalakar Dandu
62/70
Using GridBagConstriants
Only new about the code in the previous page is the final
statement:
guiConstraints.anchor = GridBagConstraints.CENTER;
The GridBagConstraints object, associated with the
GridBagLayout layout manager, contains instance variables that
can be set to govern how components are laid out. This instancevariable is used to instruct GridBagLayout on how to place a
component when it is smaller than its cell. Valid values are:
GridBagConstraints.CENTER
GridBagConstraints.NORTH
GridBagConstraints.EAST
GridBagConstraints.SOUTH
GridBagConstraints.SOUTHEAST
8/2/2019 AWT by Kamalakar Dandu
63/70
GridBagConstraints Instance Variables
The API pages for GridBagLayout explains the instance variables
used for governing component layout. These are gridx and gridy
These variables specify the characteristics of the cell at the
upper left of the components display area, where the upper left-
most cell has the address gridx=0, gridy=0. gridwidth and gridheight
These variables specify the number of cells in a row
(gridwidth) or column (gridheight) in the components display
area. The default value is 1.
fillfillis used when the components display area is larger than
the components requested size;fill determines whether (and how)
to resize the component.
Contd In Next Page...
8/2/2019 AWT by Kamalakar Dandu
64/70
ipadx and ipady
These variables specify the internal padding; that is , howmuch to add to the minimum size of the component.
insets
insets specifies the external padding of the component;
that is, the minimum amount of the space between the
component and the edges of its display area.
anchor
This variable is used when the component is smaller thanits display area; anchordetermines where to the place the
component.
8/2/2019 AWT by Kamalakar Dandu
65/70
GridBagConstraints Example
import java.awt.*;
public class GridBagLayoutDemo extends Frame {void makeButton(String name, GridBagConstraints gbc) {
Button button = new Button(name);
add(button, gbc);
}
public GridBagLayoutDemo() {setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setFont(new Font("Helvetica", Font.PLAIN, 14));
c.fill = GridBagConstraints.BOTH;c.weightx = 1.0;
makeButton("Button1", c);
makeButton("Button2", c);
makeButton("Button3", c); Contd. In Next Page..
8/2/2019 AWT by Kamalakar Dandu
66/70
c.gridwidth = GridBagConstraints.REMAINDER;//end row
makeButton("Button4", c);c.weightx = 0.0; //reset to the default
makeButton("Button5", c);//another row
//next-to-last in row
c.gridwidth = GridBagConstraints.RELATIVE;
makeButton("Button6", c);
c.gridwidth = GridBagConstraints.REMAINDER;
//end row
makeButton("Button7", c);
c.gridwidth = 1; //reset to the defaultc.gridheight = 2;
c.weighty = 1.0;
makeButton("Button8", c);
Contd. In Next Page..
8/2/2019 AWT by Kamalakar Dandu
67/70
c.weighty = 0.0; //reset to the default
c.gridwidth = GridBagConstraints.REMAINDER;//end row
c.gridheight = 1; //reset to the default
makeButton("Button9", c);
makeButton("Button10", c);
}public static void main(String args[]) {
GridBagLayoutDemo window = new GridBagLayoutDemo();
window.pack();
window.show();}
}
8/2/2019 AWT by Kamalakar Dandu
68/70
Card Layout- Create a panel for card layout
- Create different panels as cards and add to this card panel
- Change the card (panel) on some event
Example :
Panel cards;
Panel p1, p2 //for buttons, text fields ....
cards.setLayout(new CardLayout());
cards.add(ButtonPanel,p1);cards.add(TextPanel,p2);
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, ButtonPanel);
8/2/2019 AWT by Kamalakar Dandu
69/70
Lab Session
Write a program to create the login screen using Grid bag
layout.
Exercise (contd )
8/2/2019 AWT by Kamalakar Dandu
70/70
Exercise (contd)
16. A need to persist the data has now arisen asthe client observes that the development team iseither getting the data from the console or is
having it stored as string attributes in theprograms. The client wishes that the data shouldbe persisted and reused by any other programs,as well. Hence, store the data in the Collection
into a file. Implement methods to read/write thedata to/from the given file. The access methodsshould be synchronized