l23AWT Windows

advertisement
Topics
•AWT Classes
• Window Fundamentals
•Working with Frame Windows
• Creating a Frame Window in an Applet
•Creating a Windowed Program
•Displaying Information within a Window
• Working with Graphics
• Working with color
•Setting the Paint Mode
•Working with Fonts
•Managing Text Output Using Font Metrics.
AWT Classes
one of Java’s largest packages
AWT Classes
• AWT  Abstract Window Toolkit
• The main purpose of the AWT is to support applet
windows
• It can also be used to create stand-alone windows
that run in a GUI environment, such as Windows.
•The AWT classes are contained in the java.awt package
AWT Classes -
some of the original methods were deprecated
and replaced by new ones when Java 1.1 was released. For backwardcompatibility, Java 2 still supports all the original 1.0 methods.
AWT Classes
AWT Classes
AWT Classes
AWT Classes
Window Fundamentals
• The AWT defines windows according to a class hierarchy
that adds functionality and specificity with each level.
•The two most common windows are
•
those derived from Panel, which is used by applets,
•
those derived from Frame, which creates a standard
window.
Window Fundamentals
Much of the functionality of these windows is derived from their
parent classes.
- Component
• An abstract class that
• encapsulates all of the attributes of a visual
component.(All user interface elements are subclasses)
• It defines over a hundred public methods for
managing events
(such as mouse and keyboard input,
positioning and sizing the window, and repainting.)
• Remembers the current foreground and background
colors and the currently selected text font.
- Container
• A subclass of Component
• A container is responsible for laying out any
components that it contains.
• Includes methods that allow other Component
objects to be nested within it
• Other Container objects can be stored inside of a
Container
- Panel
•A Panel is a window that does not contain a title
bar, menu bar, or border.
•A concrete subclass of Container
•The superclass for Applet
•It doesn’t add any new methods; it simply
implements Container.
- Panel
• Other components can be added to a Panel
object by its add( ) method.
• add( ) method inherited from Container.
• you can position and resize the added
components manually using the setLocation( ),
setSize( ), or setBounds( ) methods defined by
Component.
- Window
•This class creates a top-level window
• A top-level window is not contained within any other
object; (it sits directly on the desktop)
• You will use a subclass of Window called Frame to create
Window objects
- Frame
•A subclass of Window and has a title bar, menu bar,
borders, and resizing corners.
• If you create a an applet window , it will contain a
warning message, such as “Java Applet Window,”
• When a Frame window is created by a program
rather than an applet, a normal window is created.
Working with Frame Windows
• It creates a standard-style window
•You will use it to create
• child windows within applets,
• top-level or child windows for applications.
Two of Frame’s constructors:
1. Frame( )  creates a standard window that does not
contain a title.
2. Frame(String title)  creates a window with the title
specified by title
Several methods are used when working with Frame
windows.
• Setting the Window’s Dimensions
1. void setSize(int newWidth, int newHeight)
2. void setSize(Dimension newSize)
newWidth and newHeight  new size of the window
newSize  the Dimension object contains width and height
fields
The dimensions are specified in terms of pixels.
3. Dimension getSize( )  used to obtain the current size of a
window
• Setting a Window’s Title
void setTitle(String newTitle)
newTitle  the new title for the window
• Closing a Frame Window
setVisible(false).
•you must implement the windowClosing( ) method of the
WindowListener interface
•Inside windowClosing( ), you must remove the window from
the screen
Creating a Frame Window in an Applet
STEPS:
1. Create a subclass of Frame.
2. Override any of the standard window methods
(init( ), start( ), stop( ), and paint( ))
3. Finally, implement the windowClosing( ) method of
the WindowListener interface
( calling setVisible(false) when the window is closed )
you create an object of frame’s subclass. This causes a frame
window to come into existence and you make window visible by
calling setVisible( ).
Note the following :
• SampleFrame calls Frame’s constructor. (with super()).
This causes a standard frame window to be created with
the title passed in title.
•This example overrides the applet window’s start( ) and
stop( ) methods. This causes the window to be removed
automatically when you terminate the applet, when you
close the window,
Sample output
Handling Events in a Frame Window
• Since Frame is a subclass of Component, it inherits all
the capabilities defined by Component.
• So you can use and manage a frame window that you
create just like you manage your applet’s main window.
• Whenever an event occurs in a window, the event
handlers defined by that window will be called.
• Each window handles its own events.
Handling Events in a Frame Window
The MouseListener Interface
1. void mouseClicked(MouseEvent me)
2. void mouseEntered(MouseEvent me)
3. void mouseExited(MouseEvent me)
4. void mousePressed(MouseEvent me)
5. void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
1. void mouseDragged(MouseEvent me)
2. void mouseMoved(MouseEvent me)
Handling Events in a Frame Window
The WindowListener Interface
1. void windowActivated(WindowEvent we)
2. void windowClosed(WindowEvent we)
3. void windowClosing(WindowEvent we)
4. void windowDeactivated(WindowEvent we)
5. void windowDeiconified(WindowEvent we)
6. void windowIconified(WindowEvent we)
7. void windowOpened(WindowEvent we)
•The following program creates a window that responds to mouse
events. The main applet window also responds to mouse events.
Sample output
It is possible to create stand-alone AWT-based
applications, too. To do this, simply create an instance of
the window or windows you need inside main( ).
Sample output
Once created, a frame window takes on a life of its own. Notice
that main( ) ends with the call to appwin.setVisible(true).
Working with
Graphics
Working with Graphics
• All graphics are drawn relative to a window.
(main window of an applet, a child window of an applet, or a stand-alone
application window.)
• The origin of each window is at the top-left corner and is 0,0.
• Coordinates are specified in pixels
• All output to a window takes place through a graphics context.
Working with Graphics
• A graphics context is encapsulated by the Graphics class and is
obtained in two ways:
•It is passed to an applet when one of its various methods, such
as paint( ) or update( ), is called.
•It is returned by the getGraphics( ) method of Component.
•The Graphics class defines a number of drawing functions.
Drawing Lines
void drawLine(int startX, int startY, int endX, int endY)
-
displays a line in the current drawing color that begins at
startX,startY and ends at endX,endY
Drawing Lines
Drawing Rectangles
1. void drawRect(int top, int left, int width, int height)
2. void fillRect(int top, int left, int width, int height)
top ,left
 The upper-left corner of the rectangle
width and height  The dimensions of the rectangle
3. void drawRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)
 draws rounded rectangle
xDiam  The diameter of the rounding arc along the X axis
yDiam  The diameter of the rounding arc along the Y axis.
Drawing Rectangles
4. void fillRoundRect(int top, int left, int width, int height, int
xDiam, int yDiam)  draws a filled rectangle
Drawing Rectangles
Sample output
Sample output
Drawing Ellipses and Circles
1. void drawOval(int top, int left, int width, int height)
2. void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left
corner is specified by top, left and whose width and height are
specified by width and height
To draw a circle, specify a square as the bounding rectangle
Drawing Ellipses and Circles
Drawing Ellipses and Circles
Sample output
Drawing Arcs
1. void drawArc(int top, int left, int width, int height, int
startAngle, int sweepAngle)
2. void fillArc(int top, int left, int width, int height, int
startAngle, int sweepAngle)
top,left  upper-left corner of the bounding rectangle
width and height  width and height of the bounding rectangle
startAngle , sweepAngle  The arc is drawn from startAngle through
the angular distance specified by sweepAngle
Drawing Arcs
• The arc is drawn counterclockwise if sweepAngle is positive,
and clockwise if sweepAngle is negative.
• Angles are specified in degrees.
•Zero degrees is on the horizontal, at the three o’clock position
To draw an arc from twelve o’clock to six o’clock, the start angle
would be 90 and the sweep angle 180.
Drawing Arcs
Drawing Arcs
Sample output
Drawing Polygons
1. void drawPolygon(int x[ ], int y[ ], int numPoints)
2. void fillPolygon(int x[ ], int y[ ], int numPoints)
•The polygon’s endpoints are specified by the coordinate pairs
contained within the x and y arrays
•numPoints The number of points defined by x and y
Drawing Polygons
Drawing Polygons
Sample output
Sizing Graphics
• To size a graphics object first obtain the current dimensions of
the window by calling getSize( ) on the window object
•Once you have the current size of the window, you can scale your
graphical output accordingly.
•getSize( ) returns the dimensions of the window encapsulated
within a Dimension object
Sizing Graphics
Sizing Graphics
Sizing Graphics
Working with
Color
Working with Color
•
Java supports color in a portable, device-independent fashion
•
Color is encapsulated by the Color class and defines constants for common
colors
•
You can also create your own colors, using one of the color constructors.
1.
Color(int red, int green, int blue)
2.
Color(int rgbValue)
3.
Color(float red, float green, float blue)
Working with Color
1. The first constructor takes three integers that specify the color
as a mix of red, green, and blue. These values must be between
0 and 255
2.
The second color constructor takes a single integer that
contains the mix of red, green, and blue packed into an integer
•red in bits 16 to 23,
• green in bits 8 to 15, and
•blue in bits 0 to 7
3. The final constructor, takes three float values (between 0.0 and
1.0) that specify the relative mix of red, green, and blue
Using Hue, Saturation, and Brightness (HSB)
• An alternative color model to red-green-blue (RGB)
•
hue  specified with a number between 0.0 and 1.0
• Saturation  ranges from 0.0 to 1.0, representing light
pastels to intense hues
• Brightness values also range from 0.0 to 1.0, where 1 is bright
white and 0 is black
Color Methods
The Color class defines several methods that help manipulate
colors.
1. static int HSBtoRGB(float hue, float saturation, float brightness)
2. static float[ ] RGBtoHSB(int red, int green, int blue, float values[ ])
3. int getRed( )  Red components of RBG
4. int getGreen( )  Green components of RBG
5. int getBlue( )  Blue components of RBG
6. int getRGB( )  packed RGB representation of a color
Setting the Current Graphics Color
You can change this color by calling the Graphics method setColor( ):
void setColor(Color newColor)
newColor  specifies the new drawing color
•You can obtain the current color by calling getColor( ),
Color getColor( )
A Color Demonstration Applet
A Color Demonstration
Applet
Setting the XOR Mode
•
By default, new output to a window overwrites any preexisting
contents.
•
However, it is possible to have new objects XORed onto the
window by using setXORMode( )
void setXORMode(Color xorColor)
xorColor  specifies the color that will be XORed to the window
when an object is drawn.
Setting the Paint Mode
• To
return to overwrite mode, call setPaintMode( ), shown here:
void setPaintMode( )
The advantage of XOR mode is that the new object is always
guaranteed to be visible no matter what color the object is drawn
over
the following program displays cross hairs that track the mouse
pointer. The cross hairs are XORed onto the window and are always
visible, no matter what the underlying color is.
Sample output
Working with Fonts
• The AWT provides
•
flexible font-manipulation
•
Allows dynamic selection of fonts.
• Fonts have
1. A family name the general name of the font, such as
Courier
2. A logical font name  specifies a category of font such as
Monospaced
3. A face name  a specific font, such as Courier Italic.
Working with Fonts
• Fonts are encapsulated by the Font class
Working with Fonts
• Some Methods Defined by Font
Working with Fonts
• Some Methods Defined by Font
Determining the Available Fonts
1.
To
obtain
font
information,
you
can
use
the
getAvailableFontFamilyNames( ) method defined by the
GraphicsEnvironment class
String[ ] getAvailableFontFamilyNames( );
This method returns an array of strings that contains the names
of the available font families.
Determining the Available Fonts
2. In addition, the getAllFonts( ) method is defined by the
GraphicsEnvironment class
Font[ ] getAllFonts( )
This method returns an array of Font objects for all of the
available fonts.
Since these methods are members of GraphicsEnvironment, you
need a GraphicsEnvironment reference to call them. You can
obtain this reference by using
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Determining the Available Fonts
Determining the Available Fonts
Sample output
Creating and Selecting a Font
To select a new font, you must first construct a Font object that
describes that font. One Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
• fontName  specifies the name of the desired font.
• fontStyle  The style of the font.
• pointSize
 The size, in points, of the font
Creating and Selecting a Font
• fontName
All Java environments will support the following fonts:
Dialog, DialogInput, SansSerif, Serif, Monospaced, and
Symbol.
• fontStyle
one or more of these three constants:
• Font.PLAIN
• Font.BOLD
• Font.ITALIC.
To combine styles, OR them together.
For example, Font.BOLD | Font.ITALIC
Creating and Selecting a Font
• To use a font that you have created, you must select it using
setFont( ), which is defined by Component
void setFont(Font fontObj)
fontObj  the object that contains the desired font
Creating and Selecting a Font
The following program outputs a sample of each standard font.
Each time you click the mouse within its window, a new font is
selected and its name is displayed
Creating and Selecting a Font
Creating and Selecting a Font
Creating and Selecting a Font
Creating and Selecting a Font
Obtaining Font Information
• To obtain information about the currently selected font, you
must first get the current font by calling getFont( ).
This method is defined by the Graphics class
Font getFont( )
Once you have obtained the currently selected font, you can
retrieve information about it using various methods defined by
Font.
Obtaining Font Information
•this applet displays the name, family, size, and style of the
currently selected font:
Obtaining Font Information
Managing Text Output
Using FontMetrics
FontMetrics class
•
Encapsulates various information about a font.
Basic Terms :
When drawString( ) method is used , the location specifies left
edge of the baseline of the characters, not at the upper-left corner
as is usual with other drawing methods
FontMetrics class
•
FontMetrics defines several methods that help you manage text
output.
FontMetrics class
•
FontMetrics defines several methods that help you manage text
output.
FontMetrics class
•
FontMetrics defines several methods that help you manage text
output.
Displaying Multiple Lines of Text Using FontMetrics
Displaying Multiple Lines of Text Using FontMetrics
Displaying Multiple Lines of Text Using FontMetrics
Displaying Multiple Lines of Text Using FontMetrics
Centering Text
Centering Text
Centering Text
Centering Text
AWT Class Hierarchy
Download