Download JSlider - Start your own free website

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Unit III Event-Driven Programming
When Java 1.0 was introduced, it contained a class library, which Sun called the Abstract Window Toolkit
(AWT), for basic GUI programming. The basic AWT library deals with user interface elements by delegating
their creation and behavior to the native GUI toolkit on each target platform
Creating a Frame
Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By default, a frame has a
size of 0 × 0 pixels and it is not visible. Frames are examples of containers. It can contain other user interface
components such as buttons and text fields.
Class hierarchy for Frame
A top-level window (that is, a window that is not contained inside another window) is called a frame in Java. The
AWT library has a class, called Frame, for this top level. The Swing version of this class is called JFrame and
extends the Frame class. The JFrame is one of the few Swing components that is not painted on a canvas. Thus,
the decorations (buttons, title bar, icons, and so on) are drawn by the user’s windowing system, not by Swing.
import javax.swing.*;
public class SimpleFrameTest
{
public static void main(String[] args)
{
Frame frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Frame extends JFrame
{
Frame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public static final int DEFAULT_WIDTH = 700;
public static final int DEFAULT_HEIGHT = 200;
}
Let’s work through this program, line by line. The Swing classes are placed in the javax.swing package. The
package name javax indicates a Java extension package, not a core package. For historical reasons, Swing is
considered an extension. However, it is present in every Java SE implementation since version 1.2. By default, a
frame has a rather useless size of 0 × 0 pixels. We define a subclass SimpleFrame whose constructor sets the size
to 300 × 200 pixels. This is the only difference between a SimpleFrame and a JFrame. In the main method of the
SimpleFrameTest class, we construct a SimpleFrame object and make it visible.
There are two technical issues that we need to address in every Swing program. First, all Swing components must
be configured from the event dispatch thread, the thread of control that passes events such as mouse clicks and
keystrokes to the user interface components. The following code fragment is used to execute statements in the
event dispatch thread:
EventQueue.invokeLater(new Runnable()
{
public void run()
{
statements
}
});
For now, you should simply consider it a magic incantation that is used to start a Swing program. Next, we define
what should happen when the user closes the application’s frame. For this particular program, we want the
program to exit. To select this behavior, we use the statement
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
In other programs with multiple frames, you would not want the program to exit just because the user closes one
of the frames. By default, a frame is hidden when the user closes it, but the program does not terminate. (It might
have been nice if the program terminated after the last frame became invisible, but that is not how Swing works.)
Simply constructing a frame does not automatically display it. Frames start their life invisible.
That gives the programmer the chance to add components into the frame before showing it for the first time. To
show the frame, the main method calls the setVisible method of the frame.
After scheduling the initialization statements, the main method exits. Note that exiting main does not terminate the
program, just the main thread. The event dispatch thread keeps the program alive until it is terminated, either by
closing the frame or by calling the System.exit method.
It is a truly boring top-level window. As you can see in the figure, the title bar and surrounding decorations, such
as resize corners, are drawn by the operating system and not the Swing library. If you run the same program in
Windows, GTK, or the Mac, the frame decorations are different. The Swing library draws everything inside the
frame. In this program, it just fills the
frame with a default background color.
Component & Window class Methods java.awt.Component
void setVisible(boolean b) - shows or hides the component depending on whether b is true or false.
void setSize(int width, int height) - resizes the component to the specified width and height.
void setBounds(int x, int y, int width, int height) - moves and resizes this component. The location of the top-left
corner is given by x and y, and the new size is given by the width and height parameters.
void setBackground(java.awt.Color) – set Background color to the window.
void setForeground(java.awt.Color)- set Foreground color to the window.
void repaint() - causes a repaint of the component ―as soon as possible.‖
java.awt.Window
void setTitle(String s) - sets the text in the title bar for the frame to the string s.
Frame’s constructors: Frame( ) - creates a standard window that does not contain a title. Frame(String title) creates a window with the title specified by title Methods of Frame class:
void setSize(int newWidth, int newHeight) - method is used to set the dimensions of the window. The
dimensions are specified in terms of pixels.
void setVisible(boolean visibleFlag)- The component is visible if the argument to this method is true.
Otherwise, it is hidden.
void setTitle(String newTitle)- change the title in a frame window.
Creating a Frame Window Method 1: In main() method
Frame f=new Frame(―frame name‖);
f.setSize(500,500);
f.setVisible(true); Example:
The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the screen.
Import java.awt package because Frame class is available in that package.
Method :2
Frame.
super(String) method call.
setSize( ) method.
setVisible() method.
Example: The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the
screen. Import java.awt package because Frame class is available in that package.
Positioning a Frame
The JFrame class itself has only a few methods for changing how frames look. Of course, through the magic of
inheritance, most of the methods for working with the size and position of a frame come from the various
superclasses of JFrame. Here are some of the most important methods:
• The setLocation and setBounds methods for setting the position of the frame
• The setIconImage method, which tells the windowing system which icon to display in the title bar, task switcher
window, and so on
• The setTitle method for changing the text in the title bar
• The setResizable method, which takes a boolean to determine if a frame will be resizeable by the user
As the API notes indicate, the Component class (which is the ancestor of all GUI objects) and the Window class
(which is the superclass of the Frame class) are where you need to look to find the methods to resize and reshape
frames. For example, the setLocation method in the Component class is one way to reposition a component. If you
make the call setLocation(x, y) the top-left corner is located x pixels across and y pixels down, where (0, 0) is the
top-left corner of the screen. Similarly, the setBounds method in Component lets you resize and relocate a
component (in particular, a JFrame) in one step, as setBounds(x, y, width, height)
Alternatively, you can give the windowing system control on window placement. If you call
setLoationByPlatform(true);
before displaying the window, the windowing system picks the location (but not the size), typically with a slight
offset from the last window.
Fig: Inheritance hierarchy for the frame and component classes in AWT and Swing
Frame Properties
Many methods of component classes come in getter/setter pairs, such as the following methods of the Frame class:
public String getTitle()
public void setTitle(String title)
Such a getter/setter pair is called a property. A property has a name and a type. The name is obtained by changing
the first letter after the get or set to lowercase. For example, the Frame class has a property with name title and
type String. Conceptually, title is a property of the frame. When we set the property, we expect that the title
changes on the user’s screen. When we get the property, we expect that we get back the value that we set.
We do not know (or care) how the Frame class implements this property. Perhaps it simply uses its peer frame to
store the title. Perhaps it has an instance field
private String title; // not required for property
If the class does have a matching instance field, we don’t know (or care) how the getter and setter methods are
implemented. Perhaps they just read and write the instance field. Perhaps they do more, such as notifying the
windowing system whenever the title changes.
There is one exception to the get/set convention: For properties of type boolean, the getter starts with is. For
example, the following two methods define the locationByPlatform property:
public boolean isLocationByPlatform()
public void setLocationByPlatform(boolean b)
Determining a Good Frame Size
Remember: if you don’t explicitly size a frame, all frames will default to being 0 by 0 pixels. To keep our example
programs simple, we resize the frames to a size that we hope works acceptably on most displays. However, in a
professional application, you should check the resolution of the user’s screen and write code that resizes the
frames accordingly: a window that looks nice on a laptop screen will look like a postage stamp on a highresolution screen. To find out the screen size, use the following steps. Call the static getDefaultToolkit method of
the Toolkit class to get the Toolkit object. (The Toolkit class is a dumping ground for a variety of methods that
interface with the native windowing system.) Then call the
getScreenSize method, which returns the screen size as a Dimension object. A Dimension object simultaneously
stores a width and a height, in public (!) instance variables width and height. Here is the code:
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
We use 50% of these values for the frame size, and tell the windowing system to position the frame:
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);
We also supply an icon. Because the representation of images is also system dependent, we again use the toolkit to
load an image. Then, we set the image as the icon for the frame:
Image img = kit.getImage("icon.gif");
setIconImage(img);
Depending on your operating system, you can see the icon in various places. For example, in Windows, the icon is
displayed in the top-left corner of the window, and you can see it in the list of active tasks when you press
ALT+TAB.
Listing 7–2 is the complete program. When you run the program, pay attention to the “Core Java” icon.
Here are a few additional tips for dealing with frames:
• If your frame contains only standard components such as buttons and text fields, you can simply call the pack
method to set the frame size. The frame will be set to the smallest size that contains all components. It is quite
common to set the main frame of a program to the maximum size. As of Java SE 1.4, you can simply maximize a
frame by calling
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
• It is also a good idea to remember how the user positions and sizes the frame of your application and restore
those bounds when you start the application again.
• If you write an application that takes advantage of multiple display screens, use the GraphicsEnvironment and
GraphicsDevice classes to find the dimensions of the display screens.
• The GraphicsDevice class also lets you execute your application in full-screen mode.
Displaying Information in a Component
In this section, we show you how to display information inside a frame. For example, rather than displaying “Not a
Hello, World program” in text mode in a console window
You could draw the message string directly onto a frame, but that is not considered good programming practice. In
Java, frames are really designed to be containers for components such as a menu bar and other user interface
elements. You normally draw on another component which you add to the frame.
The structure of a JFrame is surprisingly complex. Look at Figure 7–7, which shows the makeup of a JFrame. As
you can see, four panes are layered in a JFrame. The root pane, layered pane, and glass pane are of no interest to
us; they are required to organize the menu bar and content pane and to implement the look and feel. The part that
most concerns Swing programmers is the content pane. When designing a frame, you add components into the
content pane, using code such as the following:
Container contentPane = frame.getContentPane();
Component c = . . .;
contentPane.add(c);
Up to Java SE 1.4, the add method of the JFrame class was defined to throw an exception with the message “Do
not use JFrame.add(). Use JFrame.getContentPane().add() instead.” As of Java SE 5.0, the JFrame.add method has
given up trying to reeducate programmers, and it simply calls add on the content pane. Thus, as of Java SE 5.0,
you can simply use the call frame.add(c);
Figure 7–7 Internal structure of a JFrame
In our case, we want to add a single component to the frame onto which we will draw our message. To draw on a
component, you define a class that extends JComponent and override the paintComponent method in that class.
The paintComponent method takes one parameter of type Graphics. A Graphics object remembers a collection of
settings for drawing images and text, such as the font you set or the current color. All drawing in Java must go
through a Graphics object. It has methods that draw patterns, images, and text.
Here’s how to make a component onto which you can draw:
class MyComponent extends JComponent
{
public void paintComponent(Graphics g)
{
code for drawing
}
}
Each time a window needs to be redrawn, no matter what the reason, the event handler notifies the component.
This causes the paintComponent methods of all components to be executed. Never call the paintComponent
method yourself. It is called automatically whenever a part of your application needs to be redrawn, and you
should not interfere with this automatic process. What sorts of actions trigger this automatic response? For
example, painting occurs because the user increased the size of the window or minimized and then restored the
window. If the user popped up another window and it covered an existing window and then made the overlaid
window disappear, the application window that was covered is now corrupted and will need to be repainted. (The
graphics system does not save the pixels underneath.) And, of course, when the window is displayed
for the first time, it needs to process the code that specifies how and where it should draw the initial elements.
As you saw in the code fragment above, the paintComponent method takes a single parameter of type Graphics.
Measurement on a Graphics object for screen display is done in pixels. The (0, 0) coordinate denotes the top-left
corner of the component on whose surface you are drawing.
Displaying text is considered a special kind of drawing. The Graphics class has a drawstring method that has the
following syntax:
g.drawString(text, x, y)
In our case, we want to draw the string "Not a Hello, World Program" in our original window, roughly onequarter of the way across and halfway down. Although we don’t yet know how to measure the size of the string,
we’ll start the string at coordinates (75, 100). This means the first character in the string will start at a position 75
pixels to the right and 100 pixels down. (Actually, it is the baseline for the text that is 100 pixels down—see page
313 for more on how text is measured.) Thus, our paintComponent method looks like this:
class NotHelloWorldComponent extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
}
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
}
Listing 7–3 shows the complete code. Listing 7–3 NotHelloWorld.java
1. import javax.swing.*;
2. import java.awt.*;
8. public class NotHelloWorld
9. {
10. public static void main(String[] args)
11. {
12. EventQueue.invokeLater(new Runnable()
13. {
14. public void run()
15. {
16. NotHelloWorldFrame frame = new NotHelloWorldFrame();
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setVisible(true);
19. }
20. });
21. }
22. }
24. /**
25. * A frame that contains a message panel
26. */
27. class NotHelloWorldFrame extends JFrame
28. {
29. public NotHelloWorldFrame()
30. {
31. setTitle("NotHelloWorld");
32. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
34. // add panel to frame
36. NotHelloWorldPanel panel = new NotHelloWorldPanel();
37. add(panel);
38. }
40. public static final int DEFAULT_WIDTH = 300;
41. public static final int DEFAULT_HEIGHT = 200;
42. }
43./**
45. * A panel that displays a message.
46. */
47. class NotHelloWorldPanel extends JPanel
48. {
49. public void paintComponent(Graphics g)
50. {
51. g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
52. }
53.public static final int MESSAGE_X = 75;
55. public static final int MESSAGE_Y = 100;
56. }
Working with 2D shapes
Starting with Java 1.0, the Graphics class had methods to draw lines, rectangles, ellipses, and so on. But those
drawing operations are very limited. For example, you cannot vary the line thickness and you cannot rotate the
shapes. Java SE 1.2 introduced the Java 2D library, which implements a powerful set of graphical operations. In
this chapter, we only look at the basics of the Java 2D library.
To draw shapes in the Java 2D library, you need to obtain an object of the Graphics2D class. This class is a
subclass of the Graphics class. Ever since Java SE 2, methods such as paintComponent automatically receive an
object of the Graphics2D class. Simply use a cast, as follows:
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
...
}
The Java 2D library organizes geometric shapes in an object-oriented fashion. In particular, there are classes to
represent lines, rectangles, and ellipses:
Line2D
Rectangle2D
Ellipse2D
These classes all implement the Shape interface.
To draw a shape, you first create an object of a class that implements the Shape interface and then call the draw
method of the Graphics2D class. For example:
Rectangle2D rect = . . .;
g2.draw(rect);
Using the Java 2D shape classes introduces some complexity. Unlike the 1.0 draw methods, which used integer
pixel coordinates, the Java 2D shapes use floatingpoint coordinates. In many cases, that is a great convenience
because it allows you to specify your shapes in coordinates that are meaningful to you (such as millimeters or
inches) and then translate to pixels. The Java 2D library uses single-precision float quantities for many of its
internal floating-point calculations. Single precision is sufficient—after all, the ultimate purpose of the geometric
computations is to set pixels on the screen or printer. As long as any roundoff errors stay within one pixel, the
visual outcome is not affected. Furthermore, float computations are faster on some platforms, and float values
require half the storage of double values. However, manipulating float values is sometimes inconvenient for the
programmer because the Java programming language is adamant about requiring casts when converting double
values into float values. For example, consider the following statement:
float f = 1.2; // Error
This statement does not compile because the constant 1.2 has type double, and the compiler is nervous about loss
of precision. The remedy is to add an F suffix to the floatingpoint constant:
float f = 1.2F; // Ok
Now consider this statement:
Rectangle2D r = . . .
float f = r.getWidth(); // Error
This statement does not compile either, for the same reason. The getWidth method returns a double. This time, the
remedy is to provide a cast:
float f = (float) r.getWidth(); // Ok
Consider the Rectangle2D class. This is an abstract class with two concrete subclasses, which are also static inner
classes:
Rectangle2D.Float
Rectangle2D.Double
Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);
Actually, because both Rectangle2D.Float and Rectangle2D.Double extend the common Rectangle2D class and
the methods in the subclasses simply override methods in the Rectangle2D superclass, there is no benefit in
remembering the exact shape type. You can simply use Rectangle2D variables to hold the rectangle references.
Rectangle2D floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);
For ellipses, these refer to the bounding rectangle. For example,
Ellipse2D e = new Ellipse2D.Double(150, 200, 100, 50);
constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200), width 100, and height 50.
When constructing an ellipse, you usually know the center, width, and height, and not the corner points of the
bounding rectangle (which don’t even lie on the ellipse). The setFrameFromCenter method uses the center point,
but it still requires one of the four corner points. Thus, you will usually end up constructing an ellipse as follows:
Ellipse2D ellipse = new Ellipse2D.Double(centerX - width / 2, centerY - height / 2, width, height);
Graphics: java.awt.Graphics The Graphics class is part of the java.awt package. The Graphics class defines a
number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the
currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the
dimensions of the window, output is automatically clipped.
Java Coordinate System
Java’s coordinate system has the origin (0, 0) in the top left corner. Positive x values are to the right, and positive y
values are down. Coordinate units are measured in pixels (picture element). All pixel values are integers; there are
no partial or fractional pixels.
X coordinate: Horizontal distance moving right from the left of the screen. Y coordinate: Vertical distance moving
from top to bottom of the screen. The Graphics class provides a set of simple built-in graphics primitives for
drawing, including lines, rectangles, polygons, ovals, and arcs.
Lines: To construct a line, you supply the start and end points, either as Point2D objects or as pairs of numbers:
Line2D line = new Line2D.Double(start, end);
or
Line2D line = new Line2D.Double(startX, startY, endX, endY);
To draw straight lines, use the drawLine method. drawLine takes four arguments: the x and y coordinates of the
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.
Rectangles The Java graphics primitives provide two kinds of rectangles: Plain rectangles and Rounded
void drawRect(int x, int y, int width, int height) void
fillRect(int x, int y, int width, int height)
void drawRoundRect(int x, int y, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int x, int y, int width, int height, int xDiam, int yDiam)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at x, y. The dimensions of the
rectangle are specified by width and height. The diameter of the rounding arc along the X axis is specified by
xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam.
Example: Demo.java
import java.awt.*;
g.drawRect(100,100,60,60);
public class Demo extends Frame
g.fillRect(250,100,60,60);
{
g.drawRoundRect(100,250,60,60,10,10);
Demo(String s)
g.fillRoundRect(250,250,60,60,20,20);
{
}
super(s);
public static void main(String arg[])
setSize(500,500);
{
setVisible(true);
Demo ob=new Demo("Line Demo");
}
}
public void paint(Graphics g)
}
{
Polygons Polygons are shapes with an unlimited number of sides. Set of x and y coordinates are
needed to draw a polygon, and the drawing method starts at one, draws a line to the second, then a
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
x[]- An array of integers representing x coordinates
y[]- An array of integers representing y coordinates
numPoints- An integer for the total number of points
Example: Demo.java
import java.awt.*;
int x2[] = { 139,194,197,212,153,158,126 };
public class Demo extends Frame
int y2[] = { 133,174,136,170,208,180,206 };
{
g.fillPolygon(x2,y2,7);
public void paint(Graphics g)
}
{
public static void main(String arg[])
int x1[] = { 39,94,97,112,53,58,26 };
{
int y1[] = { 133,174,136,170,208,180,206 };
Demo ob=new Demo("Polygon Demo");
g.drawPolygon(x1,y1,7);
}}
Arc The arc is drawn from startAngle through the angular distance specified by arkAngle. Angles are specified in
degrees. The arc is drawn counterclockwise if sweepAngle is positive, and clockwise if arkAngle is negative.
drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Ovals Use ovals to draw ellipses or circles.
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
Using Color
The setPaint method of the Graphics2D class lets you select a color that is used for all subsequent drawing
operations on the graphics context. For example:
g2.setPaint(Color.RED);
g2.drawString("Warning!", 100, 100);
You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color. Simply call fill
instead of draw:
Rectangle2D rect = . . .;
g2.setPaint(Color.RED);
g2.fill(rect); // fills rect with red color
To draw in multiple colors, you select a color, draw or fill, then select another color, and draw or fill again.
You define colors with the Color class. The java.awt.Color class offers predefined constants for the
following 13 standard colors:
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE,
PINK, RED, WHITE, YELLOW
You can specify a custom color by creating a Color object by its red, green, and blue components.
Using a scale of 0–255 (that is, one byte) for the redness, blueness, and greenness, call the Color constructor
like this:
Color(int redness, int greenness, int blueness)
Here is an example of setting a custom color:
g2.setPaint(new Color(0, 128, 128)); // a dull blue-green
g2.drawString("Welcome!", 75, 125);
To set the background color, you use the setBackground method of the Component class, an ancestor of
JComponent.
MyComponent p = new MyComponent();
p.setBackground(Color.PINK);
There is also a setForeground method. It specifies the default color that is used for drawing on the
component.
Java gives you predefined names for many more colors in its SystemColor class. The constants in this class
encapsulate the colors used for various elements of the user’s system. For example,
p.setBackground(SystemColor.window)
sets the background color of the component to the default used by all windows on the user’s desktop. (The
background is filled in whenever the window is repainted.) Using the colors in the SystemColor class is
particularly useful when you want to draw user interface elements so that the colors match those already
found on the user’s desktop.
Table lists the system color names and their meanings.
Color: java.awt.Color Color class creates a solid RGB color with the specified red, green, blue value in the
range (0-255). Java’s abstract color model uses 24-bit color. The values of each color must be in the range
(0- 255). Constructor: Color(int red, int green, int blue) - create new color object for any combination of red,
green, and blue. Java.awt.Color class used to create new color object for any combination of red, green, and
blue, and it predefines a few color constants. They are stored in class variables,
Color.white (255,255,255) , Color.black (0,0,0), Color.lightGray (192,192,192) Color.gray (128,128,128)
Color.darkGray (64,64,64) ,Color.red (255,0,0), Color.green(0,255,0) Color.blue (0,0,255) Color.yellow
(255,255,0) Color.magenta (255,0,255) Color.cyan( 0,255,255) Color.pink (255,175,175) , Color.orange
(255,200,0)
java.awt.Component
Component class defines setBackground() and setForeground() methods for setting background and foreground
void
setBackground(java.awt.Color) – set Background color to the window.
void setForeground(java.awt.Color)- set Foreground color to the window.
java.awt.Graphics
setColor() method used to set the current color for the graphics context which is defined in Graphics
void setColor(java.awt.Color)
Font: java.awt.Font Font class is used to create Font Objects to set the font for drawing text, labels, textField,
buttons etc.., One Font constructor has this general form: Font(String fontName, int fontStyle, int pointSize)
Here, fontName specifies the name of the desired font. The style of the font is specified by fontStyle. It may
consist of one or more of thesethree constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. The size, in
points, of the font is specified by pointSize. point size may or may not be the height of the characters. To draw
characters in a font, first create an object of the class Font. then specify the font name, the font style, and the
point size.
Methods
Java.awt.Graphics void setFont(Font fontObj)- selects a font for the graphics context. That font will be used
for subsequent text drawing operations.
Font getFont( )- get the current font by calling getFont( ).
Java.awt.Component void setFont(Font fontObj)
Example: The following program that draws several lines of text in different fonts.
The “Not a Hello, World” program at the beginning of this chapter displayed a string in the default font.
Often, you want to show text in a different font. You specify a font by its font face name. A font face name
is composed of a font family name, such as “Helvetica,” and an optional suffix such as “Bold.” For example,
the font faces “Helvetica” and “Helvetica Bold” are both considered to be part of the family named
“Helvetica.” To find out which fonts are available on a particular computer, call the getAvailableFontFamilyNames method of the GraphicsEnvironment class. The method returns an array of strings that
contains the names of all available fonts. To obtain an instance of the GraphicsEnvironment class that
describes the graphics environment of the user’s system, use the static getLocalGraphicsEnvironment
method. Thus, the following program prints the names of all fonts on your system:
import java.awt.*;
public class ListFonts
.getAvailableFontFamilyNames();
{
for (String fontName : fontNames)
public static void main(String[] args)
System.out.println(fontName);
{
}
String[] fontNames = GraphicsEnvironment
}
.getLocalGraphicsEnvironment()
On one system, the list starts out like this:
Abadi MT Condensed Light
Arioso
Arial
Baskerville
Arial Black
BinnerGothic
Arial Narrow
. . . and goes on for another 70 fonts or so
Image: java.awt.Image Image class provides support for displaying and manipulation of graphical images. Image
is simply a rectangular graphical object.
Java provides the functions for reading images that are stored in local files and display them on graphics object.
Step1: Loading an image
java.awt.Toolkit
Toolkit getDefaultToolkit()- returns the default toolkit.
Image getImage(String filename) - returns an image that will read its pixel data from a file.
Toolkit object can only read GIF and JPEG files.
Step2: displaying an image
java.awt.Graphics
boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled image.
boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - draws a scaled
image. The system scales the image to fit into a region with the given width and height. Note: This call may
return before the image is drawn.
Example: the following program draws a tiled graphics image from the top-left corner to bottom right corner of
the window.
Once images are stored in local files or someplace on the Internet, you can read them into a Java application
and display them on Graphics objects. As of Java SE 1.4, reading an image is very simple. If the image is
stored in a local file, call
String filename = "...";
Image image = ImageIO.read(new File(filename));
Otherwise, you can supply a URL:
String urlname = "...";
Image image = ImageIO.read(new URL(urlname));
The read method throws an IOException if the image is not available.
Basics of Event Handling
Event handling is of fundamental importance to programs with a graphical user interface. To implement user
interfaces, you must master the way in which Java handles events.You will see how to capture events from
user interface components and input devices. We also show you how to work with actions, a more structured
approach for processing action events.
Most programs, to be useful, must respond to commands from the user. To do so, Java programs rely on
events that describe user actions.
Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified
of the event. All it has to do is implement the appropriate interface and be registered as an event listener on
the appropriate event source. Components can generate many kinds of events.
JAVA EVENT HANDLING MODEL
GUIs are event driven – Generate events when user interacts with GUI
Mouse movements, mouse clicks, typing in a text field, etc. – Event information stored in
object that extends AWTEvent
To process an event – Register an event listener
Object from a class that implements an event-listener interface (from java.awt.event )
"Listens" for events – Implement event handler
Method that is called in response to an event
Event handling interface has one or more methods that must be defined
Delegation event model
– Use of event listeners in event handling
– Processing of event delegated to particular object
When an event occurs
– GUI component notifies its listeners
Calls listener's event handling method.
Example
– Enter pressed in a TextField
– Method actionPerformed called for registered listener
Each event is represented by an object that gives information about the event and identifies the event source.
Event sources are typically components, but other kinds of objects can also be event sources. As the
following figure shows, each event source can have multiple listeners registered on it. Conversely, a single
listener can register with multiple event sources.
Multiple listeners can register to be notified of events of a particular type from a
particular source.
The event handling model is based on the concept of an "event listener." An object interested in receiving
events is an event listener. An object that generates events (an event source) maintains a list of listeners that
are interested in being notified when events occur, and provides methods that allow listeners to add
themselves and remove themselves from this list of interested objects. When the event source object
generates an event (or when a user input event occurs on the event source object), the event source notifies
all the listener objects that the event has occurred.
Event handling concept is quite simple: a source generates an event and sends it to one or more listeners.
Listener simply waits until it receives an event. Once received, the listener processes the event and then
returns. Events An event is an object that describes a state change in a source. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard, selecting an
item in a list, and clicking the mouse. Event Sources A source is an object that generates an event.
Sources may generate more than one type of event. A source must register listeners in order for the
listeners to receive notifications about a specific type of event.
Event Listeners Listener is an object that is notified when an event occurs. It has two major
requirements.
gistered with one or more sources to receive notifications about specific types of
events.
The package java.awt.event defines several types of events that are generated by various user interface
elements
_ HOW TO IMPLEMENT AN EVENT HANDLER ?
a listener interface.
event.
You register the listener object with the source object by using lines of code that follow the model:
eventSourceObject.addEventListener(eventListenerObject);
Every event handler requires three bits of code:
1. In the declaration for the event handler class, code that specifies that the class either implements a
listener interface or extends a class that implements a listener interface. For example:
public class MyClass implements ActionListener {
2. Code that registers an instance of the event handler class as a listener upon one or more components.
For example: someComponent.addActionListener(instanceOfMyClass);
3. Code that implements the methods in the listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action... }
Adapter classes
An adapter class provides an empty implementation of all methods in an event listener interface. It is
useful when you want to receive and process only some of the events that are handled by an event
listener interface. Define a new class that extends the adapter class and overrides the desired methods
only. Extends adapter class to create Listener and override the desired methods. If you implement the
interface, you have to define all of methods in it. This adapter class defines null methods for all events,
MouseAda
Example: If the user only interest in mouse pressed event,then simply extends MouseAdapter class and
redefine the mousePressed event. The following program listening MouseEvent whenever the user press
the mouse it will print ―mouse pressed‖ text on command prompt.
Event adapters facilitate implementing listener interfaces. Many event listener interfaces have more
than one event listener methods.
For such interfaces, Java technology defines adapter classes. These have empty implementation (stubs)
of all the event listener methods defined in the interface they implement.
A listener can subclass the adapter and override only stub methods for handling events of interest. The
table below lists the low level event listener interfaces and their adapters.
EXAMPLE OF ADAPTER CLASSES CODING
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
Toolkit.getDefaultToolkit().beep();
}}
Without extending the MouseAdapter class, I would have had to write the same class like this
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper implements MouseListener {
public void mouseClicked(MouseEvent e) {
Toolkit.getDefaultToolkit().beep();
} public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
AWT Event Hierarchy
java.awt.event
Introduction to Swing
Swing library is an official Java GUI toolkit released by Sun Microsystems
Swing Features
-and feels -- as above
o Do not depend on native peers to render themselves.
o Simplified graphics to paint on screen
o Similar behaviour across all platforms
o Portable look and feel
o Only a few top level containers not lightweight.
-- tress tables, sliders progress bars, frames, text components.
-- textual popup to give additional help
· platform independent
· extensible
· customizable
· configurable
Swing consists of the following packages
· javax.swing
· javax.swing.table
· javax.swing.border
· javax.swing.text
· javax.swing.colorchooser
· javax.swing.text.html
· javax.swing.event
Swing is probably the most advanced toolkit on this planet. It has a rich set of widgets. From basic widgets
like Buttons, Labels, Scrollbars to advanced widgets like Trees and Tables. Swing is written in 100% java.
Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured
desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and Drop. Swing was
released in 1997 with JDK 1.2. It is a mature toolkit. The Java platform has Java2D library, which enables
developers to create advanced 2D graphics and imaging.
There are basically two types of widget toolkits.
· Lightweight
· Heavyweight
A heavyweight toolkit uses OS's API to draw the widgets. For example Borland's VCL is a heavyweight
toolkit. It depends on WIN32 API, the built in Windows application programming interface. On Unix
systems, we have GTK+ toolkit, which is built on top of X11 library. Swing is a lightweight toolkit. It paints
it's own widgets. It is in fact the only lightweight toolkit I know about
On the other hand, the reasons to choose Swing are overwhelming:
• Swing has a rich and convenient set of user interface elements.
• Swing has few dependencies on the underlying platform; it is therefore less prone to platform-specific
bugs.
• Swing gives a consistent user experience across platforms.
Still, the third plus is also a potential drawback: If the user interface elements look the same on all platforms,
then they will look different from the native controls and thus users will be less familiar with the
SWT library
There is also another GUI library for the Java programming language. It is called SWT. The Standard
widget toolkit. The SWT library was initially developed by the IBM corporation. Now it is an open source
project, supported by IBM. The SWT is an example of a heavyweight toolkit. It lets the underlying OS to
create GUI. SWT uses the java native interface to do the job. The main advantages of the SWT are speed
and native look and feel. The SWT is on the other hand more error prone. It is less powerful then Swing. It
is also quite Windows centric library.
Our first example
In our first example, we will show a basic window.
import javax.swing.JFrame;
public class Simple extends JFrame {
public Simple() {
setSize(300, 200);
setTitle("Simple");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Simple simple = new Simple();
simple.setVisible(true);
}
}
while this code is very small, the application window can do quite a lot. It can be resized, maximized,
minimized. All the complexity that comes with it has been hidden from the application programmer.
import javax.swing.JFrame;
Here we import the JFrame widget. It is a toplevel container, which is used for placing other widgets.
setSize(300, 200);
setTitle("Simple");
This code will resize the window to be 300px wide and 200px tall. It will set the title of the window to
Simple.
setDefaultCloseOperation(EXIT_ON_CLOSE);
This method will close the window, if we click on the close button. By default nothing happens.
Model-View-Controller design pattern Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components. Essentially, MVC breaks GUI components into three
elements. Each of these elements plays a crucial role in how the component behaves.
The model-view-controller pattern is not the only pattern used in the design of AWT and Swing. Here are
several additonal examples:
• Containers and components are examples of the “composite” pattern.
• The scroll pane is a “decorator.”
• Layout managers follow the “strategy” pattern.
One important aspect of design patterns is that they become part of the culture. Programmers all over the
world know what you mean when you talk about the modelview- controller pattern or the “decorator”
pattern. Thus, patterns become an efficient way of talking about design problems.
Every component has three characteristics:
• Its content, such as the state of a button (pushed in or not), or the text in a text field
• Its visual appearance (color, size, and so on)
• Its behavior (reaction to events)
Implement three separate classes:
• The model, which stores the content
• The view, which displays the content
• The controller, which handles user input
The pattern specifies precisely how these three objects interact. The model stores the content and has no user
interface. For a button, the content is pretty trivial—just a small set of flags that tells whether the button is
currently pushed in or out, whether it is active or inactive, and so on. For a text field, the content is a bit
more interesting. It is a string object that holds the current text. This is not the same as the view of the
content—if the content is larger than the text field, the user sees only a portion of the text displayed.
The model must implement methods to change the content and to discover what the content is. For example,
a text model has methods to add or remove characters in the current text and to return the current text as a
string. Again, keep in mind that the model is completely
nonvisual. It is the job of a view to draw the data that is stored in the model.
Model - (includes state data for each component) The model encompasses the state data for each component.
There are different models for different types of components. Model has no user interface. Model data
always exists independent of the component's visual representation. For example, model of a Choice list
might contain the information about list of items and currently selected item. This information remains the
same no matter how the component is painted on the screen. View - (to display component on screen) The
view refers to how you see the component on the screen. It determines exactly where and how to draw the
choice list by the information offered by the model. Controller- (handles user Input) The controller decides
the behavior of each component with respect to the events. Events come in many forms (a mouse click, a
keyboard event).The controller decides how each component will react to the event—if it reacts at all.
MVC Interaction In MVC, each of the three elements—the model, the view, and the controller—requires the
services of another element to keep itself continually updated.
A Model-View-Controller Analysis of Swing Buttons
The first button will beep a sound and the second button will close the window.
JButton close = new JButton("Close");
close.setBounds(50, 60, 80, 30);
You already learned how to use buttons in the previous chapter, without having to worry about the
controller, model, or view for them. Still, buttons are about the simplest user interface elements, so they are
a good place to become comfortable with the modelview- controller pattern. You will encounter similar
kinds of classes and interfaces for the more sophisticated Swing components. For most components, the
model class implements an interface whose name ends in Model; thus the interface called ButtonModel.
Classes implementing that interface can define the state of the various kinds of buttons. Actually, buttons
aren’t all that complicated, and the Swing library contains a single class, called DefaultButtonModel, that
implements this interface. You can get a sense of what sort of data are maintained by a button model by
looking at the properties of the ButtonModel interface
Each JButton object stores a button model object, which you can retrieve.
JButton button = new JButton("Blue");
ButtonModel model = button.getModel();
In practice, you won’t care—the minutiae of the button state are only of interest to the view that draws it.
And the important information—such as whether a button is enabled—is available from the JButton class.
(The JButton then asks its model, of course, to retrieve that information.) Have another look at the
ButtonModel interface to see what isn’t there. The model does not store the button label or icon. There is no
way to find out what’s on the face of a button just by looking at its model. It is also worth noting that the
same model (namely, DefaultButtonModel) is used for push buttons, radio buttons, checkboxes, and even
menu items. Of course, each of these button types has different views and controllers. When using the Metal
look and feel, the JButton uses a class called BasicButtonUI for the view and a class called
ButtonUIListener as controller.
In general, each Swing component has an associated view object that ends in UI. But not all Swing
components have dedicated controller objects. So, having read this short introduction to what is going on
under the hood in a JButton, you may be wondering: Just what is a JButton really? It is simply a wrapper
class inheriting from JComponent that holds the DefaultButtonModel object, some view data (such as the
button label and icons), and a BasicButtonUI object that is responsible for the button view
Introduction to Layout Management
The Java Swing toolkit has two kind of components. Containers and children. The containers group children
into suitable layouts. To create layouts, we use layout managers. Layout managers are one of the most
difficult parts of modern GUI programming. Many beginning programmers have too much respect for layout
managers. Before we go on to discussing individual Swing components, such as text fields and radio
buttons, we briefly cover how to arrange these components inside a frame. Unlike Visual Basic, the JDK has
no form designer. You need to write code to position (lay out) the user interface components where you
want them to be. Of course, if you have a Java-enabled development environment, it will probably have a
layout tool that automates some or all of these tasks. Nevertheless, it is important to know exactly what goes
on “under the hood” because even the best of these tools will usually require hand-tweaking.
The buttons are contained in a JPanel
object and are managed by the flow
layout manager, the default layout
manager for a panel. Figure shows
what happens when you add more
buttons to the panel. As you can see, a
new row is started when there is no
more room.
In general, components are placed inside containers, and a layout manager determines the positions and
sizes of the components in the container. Buttons, text fields, and other user interface elements extend the
class Component. Components can be placed inside containers such as panels. Because containers can
themselves be put inside other containers, the class Container extends Component. Layout manager
automatically arranges several components within a window. Each container object has a layout manager
- Flow L
- Border Layout
Whenever a container is resized, the layout manager is used to position each of the components within it.
General syntax for setting layout to container
Void setLayout(LayouManager obj)
Arrange component without using layout Manager:
We can use no layout manager, if we want. There might be situations, where we might not need a layout
manager. For example, in my code examples, I often go without a manager. It is because I did not want to
make the examples too complex. But to create truly portable, complex applications, we need layout
managers. Without layout manager, we position components using absolute values. You can position
components manually using setBounds() method defined by Component class. 1. Disable the default
manager of your container.
setLayout(null); 2. Givethe location and size of the component which is to be added in the container.
setBounds(int x, int y, int width, int height);
eg: Button b=new Button(―click me‖);
b.setBounds(10,10,50,20);
FlowLayout FlowLayout arranges the components in rows from left-to-right and top-to-bottom order based
on the order in which they were added to the container. FlowLayout arranges components in rows, and the
alignment specifies the alignment of the rows. For example, if you create a FlowLayout that’s left aligned,
the components in each row will appear next to the left edge of the container. The FlowLayout constructors
allow you to specify the horizontal and vertical gaps that should appear between components, and if you use
a constructor that doesn’t accept these values, they both default to 5. Constructor: FlowLayout() - create
default layout, which centers component and leaves 5 pixels spaces between each component.
FlowLayout(int how)-specify how ech line is aligned.
FlowLayout(int how, int hgap, int vgap)-specify how ech line is aligned.
The flow layout manager lines the components horizontally until there is no more room and then starts a
new row of components. When the user resizes the container, the layout manager automatically reflows the
components to fill the available space. If you reduce the width of the frame further, then portions of the
wider components begin to disappear. Similarly, if you reduce the frame’s vertical size so that there’s not
enough vertical space to display all rows, some of the components will become partially or completely
inaccessible
This is the simplest layout manager in the Java Swing toolkit. It is mainly used in combination with other
layout managers. When calculating its children size, a flow layout lets each component assume its natural
(preferred) size.
The manager puts components into a row. In the order, they were added. If they do not fit into one row, they
go into the next one. The components can be added from the right to the left or vice versa. The manager
allows aligning the components. Implicitly, the components are centered and there is 5px space among
components and components and the edges of the container.
Grid Layout
The grid layout arranges all components in rows and columns like a spreadsheet. All components are given
the same size. The calculator program in uses a grid layout to arrange the calculator buttons. When you
resize the window, the buttons grow and shrink, but all buttons have identical sizes. The GridLayout layout
manager lays out components in a rectangular grid. The container is divided into equally sized rectangles.
One component is placed in each rectangle.
The GridLayout layout manager divides the available space into a grid of cells, evenly allocating the space
among all the cells in the grid and placing one component in each cell. Cells are always same size. When
you resize the window, the cells grow and s
GridLayout(int rows, int cols)cols, int hspace, int vspace) - to specify the amount of horizontal and vertical space that should appear
between adjacent components. When you create a GridLayout, you can specify a value of 0 for either the
row count or the column count, but not both. If you set the number of rows to 0, GridLayout creates as many
rows as it needs to display all the components using the specified number of columns.
Border Layout
The border layout manager is the default layout manager of the content pane of every JFrame. Unlike the flow layout
manager, which completely controls the position of each component, the border layout manager lets you choose where
you want to place each component.
A BorderLayout manager is a very handy layout manager. It divides the space into five regions. North, West, South,
East and Centre. Each region can have only one component. If we need to put more components into a region, we can
simply put a panel there with a manager of our choice. The components in N, W, S, E regions get their preferred size.
The component in the centre takes up the whole space left. It does not look good, if child components are too close to
each other. We must put some space among them. Each component in Swing toolkit can have borders around it's
edges. To create a border, we either create a new instance of an EmptyBorder class or we use a BorderFactory. Except
for EmptyBorder, there are other types of borders as well. But for layout management we will use only this one.
BorderLayout divides the container into five areas, and you can add a component to each area.
5 regions correspond to the top, left, bottom, and right sides of the container,
along with one in the center. Each of the 5 areas is associated with a constant
value defined in BorderLayout: north, south, east, west, & center for the top,
bottom, right, left, and center regions, respectively. Constructor
rLayout(int hspace, int vspace)–leave space between
components. Border layout grows all components to fill the available
space.You can add components by specifying a constraint BorderLayout.CENTER|NORTH|SOUTH|EAST|WEST void add(Component
obj, constraint)
Swing Components
javax.swing Swing components are basic building blocks of an application. Swing toolkit has a wide range
of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything a programmer needs for his job.
The JLabel Class: Swing allows you to create labels that can contain text, images, or both. Unlike
java.awt.Label objects, JLabel objects may consist of both text and graphics (icons). It does not react to
input events.
Text Input
JTextArea. The difference
between them is that a text field can accept only one line of text and a text area can accept multiple lines of
text. The classes are called JTextField for single-line input and JTextArea for multiple lines of text.
The JPasswordField Class Password fields are a special kind of text field. To avoid nosy bystanders being
able to glance at a password, the characters that the user entered are not actually displayed. Instead, each
typed character is represented by an echo character, typically an asterisk (*). The Swing set supplies a
JPasswordField class that implements such a text field.
The JButton Class They are typically used much like java.awt.Buttons. JButtons fire ActionEvents when
they are clicked.
The JCheckBox Class It is used to allow the user to turn a given
feature on or off, or to make multiple selections from a set of choices. A
JCheckBox is usually rendered by showing a small box into which a
"check" is placed when selected. The user could check either, both, or
none of the two check boxes. JCheckBox is a widget that has two states.
On and Off. It is a box with a label. If the checkbox is checked, it is
represented by a tick in a box. A checkbox can be used to show/hide
splash screen at startup, toggle visibility of a toolbar etc.
The JRadioButton Class JRadioButtons, allowing users to make a single selection from a set of options.
The JList Class A list is a graphical component from which the user can select choices. Lists typically
display several items at a time, allowing the user to make either a single selection or multiple
selections.AWT limited the contents of its List component to strings. The Swing JList component lifts this
restriction. List elements can now be strings, images. JList is a component that displays a list of objects. It
allows the user to select one or more items.
The JComboBox Class A combo box component is actually a combination of a Swing list and a text field.
Unlike lists, a combo box only allows the user one selection at a time, which is usually copied into an
editable component at the top, such as a text field. The user can be permitted, however, to manually enter in
a selection as well. JComboBox is the Swing version of a combo box component. It is very similar to the
AWT Choice component. Combobox is a component that combines a button or editable field and a dropdown list. The user can select a value from the drop-down list, which appears at the user's request. If you
make the combo box editable, then the combo box includes an editable field into which the user can type a
value.
The JPanel Class JPanel is an extension of JComponent (which, remember, extends java.awt.Container)
used for grouping together other components. It gets most of its implementation from its superclasses.
Typically, using JPanel amounts to instantiating it, setting a layout manager (this can be set in the
constructor and defaults to a FlowLayout), and adding components to it using the add() methods inherited
from Container. JTextPane component is a more advanced component for working with text. The
component can do some complex formatting operations over the text. It can display also html documents
JProgressBar A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that
the user knows, that our task is progressing. The JProgressBar widget provides a horizontal or vertical
progress bar. The initial and minimum values are 0, and the maximum is 100.
JTextArea component A JTextArea is a multi-line text area that displays plain text. It is lightweight
component for working with text. The component does not handle scrolling. For this task, we use
JscrollPane component.
JSlider
JSlider is a component that lets the user graphically select
a value by sliding a knob within a bounded interval. Our
example will show a volume control.
JToggleButton
JToggleButton is a button that has two states. Pressed
and not pressed. You toggle between these two states by
clicking on it. There are situations where this
functionality fits well