0% found this document useful (0 votes)
2 views23 pages

Chapter 8

The document discusses graphics programming in Java, focusing on user interfaces (CUI vs. GUI) and the use of the Abstract Window Toolkit (AWT) and Swing for GUI development. It explains the creation of frames using JFrame, methods associated with JFrame, and how to display content in components. Additionally, it covers Java 2D for advanced graphical operations, including drawing shapes with the Graphics2D class.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Chapter 8

The document discusses graphics programming in Java, focusing on user interfaces (CUI vs. GUI) and the use of the Abstract Window Toolkit (AWT) and Swing for GUI development. It explains the creation of frames using JFrame, methods associated with JFrame, and how to display content in components. Additionally, it covers Java 2D for advanced graphical operations, including drawing shapes with the Graphics2D class.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Graphics Programming 8.

8 Graphics Programming
Graphics Programming
User interaction with the program is of two types:
· CUI (Character User Interface): In CUI user interacts with the application
by typing characters or commands. In CUI user should remember the
commands. It is not user friendly.
· GUI (Graphical User Interface): In GUI user interacts with the
application through graphics. GUI is user friendly. GUI makes application
attractive. It is possible to simulate real object in GUI programs.
Using GUI you can learn how to write programs that size and locate windows on the
screen, display text with multiple fonts in a window, display images, and so on.
Abstract Window Toolkit
In java to write GUI programs we can use awt (Abstract Window Toolkit)
package. The package java.awt - Contains all of the classes for creating user interfaces
and for painting graphics and images as shown in the figure 8.1 shows the Java AWT
Component Class Hierarchy.

8.1 Introducing Swings


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 (Windows, Solaris, Macintosh, and so on). The
resulting program could then, in theory, run on any of these platforms, with the "look and
feel" of the target platform—hence Sun's trademarked slogan "Write Once, Run
Anywhere."

Swing was became a part of the standard library in java SE 1.2. Swing is not a
complete replacement for the AWT.
Swing is part of the Java Foundation Classes (JFC).

Reason to Choose Swing:


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

Draw Back
 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 them.
8.2 Java Programming Paradigms

Color
Button
Font
Canvas Panel
Graphics
Object Container
Dialog
java.lang
Window
. Component Label
Frame

Scroll Bar

Text Component

Menu Bar
Menu Component

Menu Item

Border Layout
Layout Manager
Grid Layout

Event

Figure 8.1 The Java AWT Component Class Hierarchy.

8.2 Creating a 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.
The swing classes are placed in the javax.swing package. The package name
javax indicates Java extension package, not a core package.
ATTENTION: Most Swing component classes start with a "J": JButton, JFrame, and so
on. There are classes such as Button and Frame, but they are AWT components. If you
accidentally omit a "J", your program may still compile and run, but the mixture of
Swing and AWT components can lead to visual and behavioral inconsistencies.
Graphics Programming 8.3

JFrame Constructor

Constructor Description
JFrame() Constructs a new frame that is initially
invisible.
JFrame(GraphicsConfiguration gc) Creates a Frame in the specified
GraphicsConfiguration of a screen device
and a blank title.
JFrame(String title) Creates a new, initially invisible Frame
with the specified title.
JFrame(String title, GraphicsConfiguration Creates a JFrame with the specified title
gc) and the specified GraphicsConfiguration
of a screen device.
Table 8.1 JFrame Constructors

JFrame Methods

Following table 8.2 shows some of the methods in JFrame


int Returns the operation that occurs when
getDefaultCloseOperation() the user initiates a "close" on this
frame.
void Sets the operation that will happen by
setDefaultCloseOperation(int operation) default when the user initiates a
"close" on this frame.
void Sets the image to be displayed as the
setIconImage(Image image) icon for this window.

void setTitle(String title) Sets the title for this frame to the
specified string.
String getTitle() Gets the title of the frame. The title is
displayed in the frame's border.
Image getIconImage() Returns the image to be displayed as
the icon for this frame.
void setResizable(boolean resizable) Sets whether this frame is resizable by
the user.
void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the
specified menu bar.
Table 8.2 JFrame Methods
8.4 Java Programming Paradigms

Creating the Frame:


· We can create a JFrame by creating JFrame class object.
JFrame obj = new JFrame ();
(or)
Create a class that extends Frame class then create an object to that class.
class MyClass extends JFrame
MyClass obj = new MyClass();
· After creating the Frame we need to set Frame width and height using setSize
() method as:
obj.setSize (400, 350);
· We can display the frame using setVisible () method as:
obj.setVisible (true);

import javax.swing.*;
public class JFrameDemo
{
public static void main(String[] args)
{
JFrame jf=new JFrame("JFrameDemo");
jf.setSize(200,200);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.show();
}
}
Program 8.1 Creating JFrame class using object

Output

From the above output the frame size will be (200,200) in x and y axis respectively. And
the “JFrameDemo” will be deisplayed in the title bar by JFrame constructor. Next
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); will exists the window.
Graphics Programming 8.5

import javax.swing.*;
public class JFrameExtends
{
public static void main(String[] args)
{
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SimpleFrame extends JFrame
{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
public SimpleFrame()
{
setTitle("JFrameExtends");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
Program 8.2 Creating JFrame class using extends method
Output

8.3 Displaying information in a Component


A component is an object having a graphical representation that can be displayed
on the screen and that can interact with the user. Examples of components are the
buttons, checkboxes, and scrollbars of a typical graphical user interface.

The Component class is the abstract superclass of the nonmenu-related Abstract


Window Toolkit components. Class Component can also be extended directly to create
8.6 Java Programming Paradigms

a lightweight component. A lightweight component is a component that is not associated


with a native opaque window.

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 JFrameclass 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.addmethod 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 8.2 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.
Graphics Programming 8.7

The paint Component 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:

classMyComponent 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.
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, 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.

classNotHelloWorldComponent extends JComponent


{
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;

public void paintComponent(Graphics g)


{
g.drawString("Not a Hello, World program", MESSAGE_X,
MESSAGE_Y);
}
}

NOTE: Instead of extending JComponent, some programmers prefer to extend the JPanel
class. A JPanel is intended to be a container that can contain other components, but it is
also possible to paint on it. There is just one difference. A panel is opaque, which means
that it is responsible for painting all pixels within its bounds. The easiest way to achieve
8.8 Java Programming Paradigms

that is to paint the panel with the background color, by calling super .paintComponentin
the paint Component method of each panel subclass:

classNotHelloWorldPanel extends JPanel


{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
. . . // code for drawing will go here
}
}
public class NotHelloWorld
{
public static void main(String[] args)
{
NotHelloWorldFrame frame = new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//A frame that contains a message panel
class NotHelloWorldFrame extends JFrame
{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
NotHelloWorldPanel panel = new NotHelloWorldPanel(); // add panel to frame
add(panel);
}
}
// A panel that displays a message.
class NotHelloWorldPanel extends JPanel
{
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
}}
Program 8.3 To display content in JComponent or in JPanel
Graphics Programming 8.9

Output

8.4 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.
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.
NOTE: The Java 2D library supports more complex shapes—in particular, arcs,
quadratic and cubic curves, and general paths.

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);
8.10 Java Programming Paradigms

NOTE: Before the Java 2D library appeared, programmers used methods of the
Graphics class such as drawRectangle to draw shapes.

The Java 2D shapes use floating-point 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 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
floating point 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
Because the suffixes and casts are a bit of a pain, the designers of the 2D library
decided to supply two versions of each shape class: one with float coordinates for frugal
programmers, and one with double coordinates for the lazy ones.
Rectangle2D class is an abstract class with two concrete subclasses, which are also static
inner classes: as shown in the diagram
Rectangle2D.Float
Rectangle2D.Double

Rectangle2D

Rectangle2D.Float Rectangle2D.Double

Figure 8.3 2D rectangle classes

When you construct a Rectangle2D.Float object, you supply the coordinates as


float numbers. For a Rectangle 2D.Double object, you supply them as double numbers.
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);
Graphics Programming 8.11

Actually, because both Rectangle 2D.Float and Rectangle 2D.Double extend the
common Rectangle 2D class and the methods in the subclasses simply override methods
in the Rectangle 2D 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);
That is, you only need to use the pesky inner classes when you construct the shape
objects. The construction parameters denote the top-left corner, width, and height of the
rectangle.
The Rectangle2D methods use double parameters and return values. For example, the get
Width method returns a double value, even if the width is stored as a float in a Rectangle
2D.Float object.
TIP: Simply use the Double shape classes to avoid dealing with float values
altogether. However, if you are constructing thousands of shape objects, then you can
consider using the Float classes to conserve memory.
Furthermore, there is a Point2D class with sub classes Point2D .Float and Point2D
.Double. Here is how to make a point object.
Point2D p = new Point2D.Double(10, 20);

Figure 8.4 The bounding rectangle of an ellipse

The classes Rectangle2D and Ellipse2D both inherit from the common superclass
Rectangular Shape. Admittedly, ellipses are not rectangular, but they have a bounding
rectangle .

The Rectangular Shape class defines over 20 methods that are common to these
shapes, among them such useful methods as get Width, getHeight, getCenterX, and
getCenterY(but sadly, at the time of this writing, not a get Center method that returns the
center as a Point2D object).

Finally, a couple of legacy classes from Java 1.0 have been fitted into the shape
class hierarchy.The Rectangle and Point classes, which store a rectangle and a point with
integer coordinates, extend the Rectangle2D and Point2D classes.
8.12 Java Programming Paradigms

Point2D Shape

Point Line2D Rectangle


shape

Ellipse2D Rectangle2D

Rectangle

Figure 8.5 Relationships between the shape classes

The figure 8.5 shows the Relationships between the shape classes. However, the Double
and Float subclasses are omitted. Legacy classes are marked with a gray fill.
Rectangle2D and Ellipse 2D objects are simple to construct. You need to specify

 The x- and y-coordinates of the top-left corner; and


 The width and height.
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.
If you isn’t the point on top-left corner, one or both of the coordinate differences
will be negative and the rectangle will come out empty. In that case, first create a blank
rectangle and use the setFrameFromDiagonal method, as follows:
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);

Or, even better, if you know the corner points as Point2D objects p and q, then
rect.setFrameFromDiagonal(p, q);

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:
Graphics Programming 8.13

Ellipse2D ellipse = new Ellipse2D.Double(centerX - width / 2, centerY


- height / 2, width, height);

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

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class DrawTest


{
public static void main(String[] args)
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//A frame that contains a panel with drawings
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
DrawPanel panel = new DrawPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
//A panel that displays rectangles and ellipses.
class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
8.14 Java Programming Paradigms

double leftX = 100;


double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle with the same center
double centerX = rect.getCenterX();
double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
}
Program 8.4 Example Program for drawing geometric shapes
Output

java.awt.geom.RectangularShape
 doublegetCenterX()
 doublegetCenterY()
 doublegetMinX()
 doublegetMinY()
Graphics Programming 8.15

 doublegetMaxX()
 doublegetMaxY()
returns the center, minimum, or maximum x- or y-value of the enclosing rectangle.
 doublegetWidth()
 doublegetHeight()
returns the width or height of the enclosing rectangle.
 doublegetX()
 double getY()
returns the x- or y-coordinate of the top-left corner of the enclosing rectangle.

java.awt.geom.Rectangle2D.Double
 Rectangle2D.Double(double x, double y, double w, double h)
constructs a rectangle with the given top-left corner, width, and height.
 Rectangle2D.Float(float x, float y, float w, float h)
constructs a rectangle with the given top-left corner, width, and height.
java.awt.geom.Ellipse2D.Double
 Ellipse2D.Double(double x, double y, double w, double h)
constructs an ellipse whose bounding rectangle has the given top-left corner,
width, and height.
java.awt.geom.Point2D.Double
 Point2D.Double(double x, double y)
constructs a point with the given coordinates.
 Line2D.Double(Point2D start, Point2D end)
 Line2D.Double(double startX, double startY, double endX, double endY).
constructs a line with the given start and end points.

8.5 Using Color

The set Paint 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
8.16 Java Programming Paradigms

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 .Colorclass 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 set Background method of the
Component class, an ancestor of JComponent.
MyComponent p = new MyComponent();
p.setBackground(Color.PINK);
There is also a set Foreground 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 SystemColorclass.
The constants in this class encapsulate the colors used for various elements of the user’s
system.
For example,
p.setBackground(SystemColor.window)
will sets the background color of the component to the default used by all windows on the
user’s desktop.

8.6 Using special fonts for text


To draw characters in a font, you must first create an object of the class Font. You
specify the font face name, the font style, and the point size. Here is an example of how
you construct a Font object:
Font sansbold14 = new Font("SansSerif", Font.BOLD, 14);
Graphics Programming 8.17

The third argument is the point size. Points are commonly used in typography to
indicate the size of a font. There are 72 points per inch.

You can use a logical font name in the place of a font face name in the Font
constructor. You specify the style (plain, bold, italic, or bold italic) by setting the second
Font constructor argument to one of the following values:

Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC

The font is plain with a font size of 1 point. Use the deriveFontmethod to get a font of the
desired size:

Font f = f1.deriveFont(14.0F);

the code that displays the string “Hello, World!” in the standard sans serif font on your
system, using 14-point bold type:

Font sansbold14 = new Font("SansSerif", Font.BOLD, 14);


g2.setFont(sansbold14);
String message = "Hello, World!";
g2.drawString(message, 75, 100);

Next, let’s center the string in its component rather than drawing it at an arbitrary
position. We need to know the width and height of the string in pixels. These dimensions
depend on three factors:

 The font used (in our case, sans serif, bold, 14 point);
 The string (in our case, “Hello, World!”); and
 The device on which the font is drawn (in our case, the user’s screen).

To obtain an object that represents the font characteristics of the screen device, you
call the get Font Render Context method of the Graphics2D class. It returns an object of
the Font -Render Context class. You simply pass that object to the get String Bounds
method of the Font

class:
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds(message, context);
8.18 Java Programming Paradigms

The getStringBounds method returns a rectangle that encloses the string.

Baseline is the imaginary line where, for example, the bottom of a character like “e”
rests.

Ascent is the distance from the baseline to the top of an ascender, which is the upper part
of a letter like “b” or “k,” or an uppercase character.

Descent is the distance from the baseline to a descender, which is the lower portion of a
letter like “p” or “g”.

Figure 8.6 Typesetting terms illustrated


Leading is the space between the descent of one line and the ascent of the next line.
Height of a font is the distance between successive baselines, which is the same as
descent + leading + ascent.

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class FontTest
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

/**
A frame with a text message panel
*/
class FontFrame extends JFrame
Graphics Programming 8.19

{
public FontFrame()
{
setTitle("FontTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
FontPanel panel = new FontPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

/**
A panel that shows a centered message in a box.
*/
class FontPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;

String message = "Hello, World!";

Font f = new Font("Serif", Font.BOLD, 34);


g2.setFont(f);

// measure the size of the message

FontRenderContext context = g2.getFontRenderContext();


Rectangle2D bounds = f.getStringBounds(message, context);

// set (x,y) = top left corner of text

double x = (getWidth() - bounds.getWidth()) / 2;


double y = (getHeight() - bounds.getHeight()) / 2;

// add ascent to y to reach the baseline

double ascent = -bounds.getY();


double baseY = y + ascent;
8.20 Java Programming Paradigms

// draw the message

g2.drawString(message, (int) x, (int) baseY);


g2.setPaint(Color.blue);
// draw the baseline

g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));


// draw the enclosing rectangle
Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(),
bounds.getHeight());
g2.draw(rect);
}
}
Program 8.5 Example for text color and font
Output

8.7 Displaying Images

If we want to load the image from local file or from internet and to store in a local
file, use the coding

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 IOExceptionif the image is not available. For now,
our sample program just catches that exception and prints a stack trace if it occurs.

Now the variable image contains a reference to an object that encapsulates the
image data. You can display the image with the draw Image method of the Graphics
class.
Graphics Programming 8.21

public void paintComponent(Graphics g)


{
...
g.drawImage(image, x, y, null);
}

We first draw one copy of the image in the top-left corner and then use
thecopyAreacall to copy it into the entire window:

for (int i = 0; i * imageWidth<= getWidth(); i++)


for (int j = 0; j * imageHeight<= getHeight(); j++)
if (i + j > 0)
g.copyArea(0, 0, imageWidth,imageHeight, i * imageWidth, j * imageHeight);
Example Program:
import java.awt.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class ImageTest


{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ImageFrame frame = new ImageFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

// A frame with an image component


class ImageFrame extends JFrame
{
public ImageFrame()
{
setTitle("ImageTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
8.22 Java Programming Paradigms

// add component to frame


ImageComponent component = new ImageComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

// A component that displays a tiled image


class ImageComponent extends JComponent
{
public ImageComponent()
{
// acquire the image
try
{
image = ImageIO.read(new File("blue-ball.gif"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
if (image == null) return;
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
// draw the image in the upper-left corner
g.drawImage(image, 0, 0, null);
// tile the image across the component
for (int i = 0; i * imageWidth <= getWidth(); i++)
for (int j = 0; j * imageHeight <= getHeight(); j++)
if (i + j > 0) g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j
* imageHeight);
}
private Image image;
}
Program 8.6 Example for Image Display
Graphics Programming 8.23

Output

Review Questions

Part-A
1. Explain the properties of frame.
2. What are the steps needed to show a Frame?
3. What is a JPanel object?

Part-B
1) How to create a frame with example program?
2) Write a program to display the content in the frame with explanation.
3) Write a program for drawing geometric shapes.
4) Write a program for example of text color and font.
5) Write a program to display an image.

You might also like