Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts

Friday, 24 June 2011

Swing : Displaying Images

By now, you know how to create a frame, how to draw shapes, how to write out text and alter the fonts of the text. The last thing needed for us to start creating nice UI components, is our ability to display images. This is exactly what we are going to learn in this chapter.

So, lets get started!!!

Displaying Photos & Images:

Java Swings has a lot of nice features and one of them is the ability to display images on its components. You can select any image that is available in the local system or somewhere on the internet and display it on Graphics objects. As of Java SE 1.4, reading an image is very simple.

If the image is stored in a local file:

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.

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

public void paintComponent(Graphics g)
{
. . .
g.drawImage(image, x, y, null);
}

Sometimes, you may want to tile an image across a components canvas if it is much smaller than the component size. We can do the tiling in the paintComponent method. We first draw one copy of the image in the top-left corner and then use the copyArea call to copy it into the entire window using the code below:

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

Code Example:

Let us now take a look at a fully functional code example that displays as well as tiles an image.

Note: The image I am displaying is available in the My Pictures directory in my computer and you have to provide the correct path to any image that you wish to display. Otherwise only a blank frame will come up.

import java.awt.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

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

/**
 * A frame with an image component
 */
class MyImageFrame extends JFrame
{
public MyImageFrame()
{
setTitle("ImageTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add component to frame

MyImageComponent component = new MyImageComponent();
add(component);
}

public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 500;
}

/**
 * A component that displays a tiled image
 */
class MyImageComponent extends JComponent
{
public MyImageComponent()
{
// get the image
try
{
image = ImageIO.read(new File("H:\\Personal\\My Pictures\\somepic.JPG"));
}
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 top-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;
}

Basics of Event Handling

What is Event Handling?

Any operating environment that supports GUIs constantly monitors events such as keystrokes or mouse clicks. The operating environment reports these events to the programs that are running. Each program then decides what, if anything, to do in response to these events. For example, if you use the start menu and then click on My Computer, the OS identifies the fact that you want to view the details of your computer and opens up the Explorer window. The click on the icon is an event and the opening of the explorer window is how the OS handles the event.

As one would expect in an object-oriented language like Java, the information about the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class java.util.EventObject. Of course, there are subclasses for each event type, such as ActionEvent and WindowEvent.
Different event sources can produce different kinds of events. For example, a button can send ActionEvent objects, whereas a window can send WindowEvent objects.

Below is how Events are handled in AWT:
• A listener object is an instance of a class that implements a special interface called a listener interface.
• An event source is an object that can register listener objects and send them event objects.
• The event source sends out event objects to all registered listeners when that event occurs.
• The listener objects will then use the information in the event object to determine their reaction to the event.

Look at the image below to understand the relationship between event sources and listeners.

Below is how you will specify a listener to a component, say a Button.
Now the listener object is notified whenever an “action event” occurs in the button. For buttons, as you rightly guessed, an action event is a button click.

To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.
ActionListener listener = . . .;
JButton button = new JButton("Ok");
button.addActionListener(listener);
To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.
class MyListener implements ActionListener{
. . .
public void actionPerformed(ActionEvent event) {
// code to handle button click goes here
. . .
}
}

Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls listener.actionPerformed(event), passing that event object. An event source such as a button can have multiple listeners. In that case, the button calls the actionPerformed methods of all listeners whenever the user clicks the button.

You can understand the event notification system by looking at the image below:

A Working Example:

Let us wrap up this chapter by looking at a full fledged example.

Let us say we want to have 3 buttons in our screen and 3 different actions must happen when the user clicks on them. For simplicity lets have the screen filled with 3 different colors when the user clicks on each of them.

Code:

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

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

/**
 * A frame with a button panel
 */
class MyTestFrame extends JFrame
{
public MyTestFrame()
{
setTitle("Button Action Test");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// create buttons
JButton redButton = new JButton("Red");
JButton blueButton = new JButton("Blue");
JButton greenButton = new JButton("Green");

buttonPanel = new JPanel();

// add buttons to panel
buttonPanel.add(redButton);
buttonPanel.add(blueButton);
buttonPanel.add(greenButton);

// add panel to frame
add(buttonPanel);

// create button actions
HandleActions greenAction = new HandleActions(Color.GREEN);
HandleActions blueAction = new HandleActions(Color.BLUE);
HandleActions redAction = new HandleActions(Color.RED);

// associate actions with buttons
greenButton.addActionListener(greenAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}

/**
     * An action listener that sets the panel's background color.
     */
private class HandleActions implements ActionListener
{
public HandleActions(Color c)
{
backgroundColor = c;
}

public void actionPerformed(ActionEvent event)
{
buttonPanel.setBackground(backgroundColor);
}

private Color backgroundColor;
}

private JPanel buttonPanel;

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}



If you compile and run this class your output will be like below:
On click of Red
On click of blue:
On click of green :




Swing : Using Special Fonts for Text

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

Finding the list of all Available Fonts:

To find out the fonts that 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.

Try executing the below sample program:

import java.awt.*;

public class ListAllFontsInMyPC
{
public static void main(String[] args)
{
String[] fontNames = GraphicsEnvironment
  .getLocalGraphicsEnvironment()
  .getAvailableFontFamilyNames();
  for (String fontName : fontNames)
    System.out.println(fontName);
  }
}

On my PC, I get a list of fonts that starts like below:

Agency FB
Aharoni
Akzidenz Grotesk CE Light
Akzidenz Grotesk CE Roman
Akzidenz Grotesk Light
Akzidenz Grotesk Roman
AkzidenzGrotesk
AkzidenzGroteskCE
Algerian
Andalus
Angsana New
AngsanaUPC

Note: There are over 200 fonts in my PC and the whole list will be too big to print out here. So, I have just put in the first 12 fonts. You can run this in your PC to see what all fonts are installed/available in your system.

To establish a common baseline, the AWT defines five logical font names:

SansSerif
Serif
Monospaced
Dialog
DialogInput

These names are always mapped to fonts that actually exist on the client machine. For example, on a Windows system, SansSerif is mapped to Arial.

In addition, the Sun JDK always includes three font families named “Lucida Sans,” “Lucida Bright,” and “Lucida Sans Typewriter.”

Creating a Font Object:

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.

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

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. The bigger the number here, the larger the font size would be…

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

You can read font files in TrueType or PostScript Type 1 formats. You need an input stream for the font—typically from a file or URL. Then call the static Font.createFont method like below:

URL url = new URL("http://www.fonts.com/Wingbats.ttf");
InputStream in = url.openStream();
Font f1 = Font.createFont(Font.TRUETYPE_FONT, in);

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

Font f = f1.deriveFont(14.0F);

Trivia:
There are two overloaded versions of the deriveFont method. One of them (with a float parameter) sets the font size, the other (with an int parameter) sets the font style. Thus, f1.deriveFont(14) sets the style and not the size! (The result is an italic font because it happens that the binary representation of 14 sets the ITALIC bit but not the BOLD bit.)

Using a Font:

Once you create a font object, you can use it to affect a string that will be displayed on screen.
For ex:

Font sansbold14 = new Font("SansSerif", Font.BOLD, 14);
g2.setFont(sansbold14);
String message = "Hey Buddy!!! !";
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, “Hey Buddy!!!”); 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 getFontRenderContext method of the Graphics2D class. It returns an object of the FontRenderContext class. You simply pass that object to the getStringBounds method of the Font class:

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

The getStringBounds method returns a rectangle that encloses the string.

To interpret the dimensions of that rectangle, you should know some basic typesetting terms. Look at the image below:

The baseline is the imaginary line where, for example, the bottom of a character like “e” rests. The 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. The descent is the distance from the baseline to a descender, which is the lower portion of a letter like “p” or “g.”

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

  • The width of the rectangle that the getStringBounds method returns is the horizontal extent of the string.
  • The height of the rectangle is the sum of ascent, descent, and leading. 
  • The rectangle has its origin at the baseline of the string. 
  • The top y-coordinate of the rectangle is negative.

So, you can obtain string width, height, and ascent as follows:

double stringWidth = bounds.getWidth();
double stringHeight = bounds.getHeight();
double ascent = -bounds.getY();

If you need to know the descent or leading, you need to use the getLineMetrics method of the Font class. That method returns an object of the LineMetrics class, which has methods to obtain the descent and leading:

LineMetrics metrics = f.getLineMetrics(message, context);
float descent = metrics.getDescent();
float leading = metrics.getLeading();

The following code example uses all this information to center a string in its surrounding component:

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

// (x,y) for getting 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;
g2.drawString(message, (int) x, (int) baseY);

To understand the centering, consider that getWidth() returns the width of the component. A portion of that width, namely, bounds.getWidth(), is occupied by the message string. The remainder should be equally distributed on both sides. Therefore, the blank space on each side is half the difference. The same reasoning applies to the height.

A Fully Functional Code Example:

Let us now take a look at a fully functional code example that will print out some text and then center it.

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

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

/**
 * A frame with a text message component
 */
class MyFrame extends JFrame
{
public MyFrame()
{
setTitle("Test Fonts");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add component to frame
MyFontComponent component = new MyFontComponent();
add(component);
}

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

/**
 * A component that shows a centered message in a box.
 */
class MyFontComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;

String message = "Hey Buddy!!!";

Font f = new Font("Serif", Font.BOLD, 36);
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;

// draw the message
g2.drawString(message, (int) x, (int) baseY);
g2.setPaint(Color.LIGHT_GRAY);

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


Swing : Using Colors

Now that we know how to create various 2D shapes, the next step would be to use colors in our UI components. Not everything looks fine in black and white. Colors bring some radiance and class to the look and feel of a UI component. In this chapter, we are going to learn how to do just that.

So, lets get started!!!

Using Colors:

The setPaint method of the Graphics2D class lets you select a color that will be used for all subsequent drawing operations on the graphics context. For example:

g2.setPaint(Color.RED);
g2.drawString("Caution!", 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 the rect object 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 and then invoke the Color constructor like below:

Color(int redness, int greenness, int blueness)

Example:
g2.setPaint(new Color(0, 128, 128));
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.MAGENTA);

There is also a setForeground method. It specifies the default color that is used for drawing on the component.


Trivia:
The brighter() and darker() methods of the Color class produce, as their names suggest, either brighter or darker versions of the current color. Using the brighter method is also a good way to highlight an item. Actually, brighter() is just a little bit brighter. To make a color really stand out, apply it three times: c.brighter().brighter().brighter().

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.

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.

Let us now take a look at all the possible color options available in the System Color class and their usage.
Name Usage/Purpose
desktop Background color of desktop
activeCaption Background color for captions
activeCaptionText Text color for captions
activeCaptionBorder Border color for caption text
inactiveCaption Background color for inactive captions
inactiveCaptionText Text color for inactive captions
inactiveCaptionBorder Border color for inactive captions
window Background for windows
windowBorder Color of window border frame
windowText Text color inside windows
menu Background for menus
menuText Text color for menus
text Background color for text
textText Text color for text
textInactiveText Text color for inactive controls
textHighlight Background color for highlighted text
textHighlightText Text color for highlighted text
control Background color for controls
controlText Text color for controls
controlLtHighlight Light highlight color for controls
controlHighlight Highlight color for controls
controlShadow Shadow color for controls
controlDkShadow Dark shadow color for controls
scrollbar Background color for scrollbars
info Background color for spot-help text
infoText Text color for spot-help text

Swing : Creating 2-Dimensional 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 will only look at the basics of the Java 2D library. The advanced features will be covered subsequently in one of the future chapters.
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.

How to Draw a 2D Shape?

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 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 them to pixels. The Java 2D library uses single-precision float quantities for many of its internal floating-point calculations. Single precision is sufficient in most cases; 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. To add on, 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 becomes conscious about loss of precision and starts to complain. The solution is to add an F suffix to the floating-point constant:

float f = 1.2F; // Ok

This will tell the complier something like “Hey I know what I am doing, I have explicitly casted this number to a float, so don't complain and carry on with the compilation”

Lets say you do something like below:
Rectangle2D r = . . .
float f = r.getWidth(); // Error

This statement does not compile either and you receive an error. This is because, the getWidth method returns a double and the compiler is having the same problem it had a few lines before. This time, the solution is to provide an explicit cast:
float f = (float) r.getWidth();

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 conscious programmers, and one with double coordinates for the lazy ones (like you and me).

The Rectangle2D Class:
The Rectangle2D class is an abstract class with two concrete subclasses, which are also static inner classes:
Rectangle2D.Float
Rectangle2D.Double

The below image shows the inheritance diagram of this class.

It is best to try to ignore the fact that the two concrete classes are static inner classes. That is just done to avoid names such as FloatRectangle2D and DoubleRectangle2D.
When you construct a Rectangle2D.Float object, you supply the coordinates as float numbers. For a Rectangle2D.Double object, you supply them as double numbers.

For Ex:

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. Therefore, there is no benefit in remembering the exact shape type. You can simply use Rectangle2D variables to hold the rectangle references like below instead of our previous example.

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

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 getWidth method returns a double value, even if the width is stored as a float in a Rectangle2D.Float object.

What we just discussed for the Rectangle2D classes holds for the other shape classes as well.

Creating a Point (Dot):
There is a Point2D class with subclasses Point2D.Float and Point2D.Double. (Just like the Rectangle class)

Below is how you can make a point object:
Point2D p = new Point2D.Double(10, 20);

Drawing Ellipses

The classes Rectangle2D and Ellipse2D both inherit from the common superclass RectangularShape. Even though, ellipses are not rectangular, they do have a bounding rectangle. Look at the image below:

As you can see, the ellipse would fit in properly inside a rectangle.

The RectangularShape class defines over 20 methods that are common to these shapes, among them such useful methods as getWidth, getHeight, getCenterX, and getCenterY.

Rectangle2D and Ellipse2D 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);

The line of code above constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200), width 100, and height 50.

However, sometimes you don’t have the top-left corner readily available. It is quite common to have two diagonal corner points of a rectangle, but perhaps they aren’t the top-left and bottom-right corners. You can’t simply construct a rectangle as

Rectangle2D rect = new Rectangle2D.Double(px, py, qx - px, qy - py); // Error


If p isn’t the 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:

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


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


A Sample Program incorporating all the shapes we learnt:

Let us wrap up this chapter, with a sample program that will draw all the shapes we just saw in the preceding paragraphs.

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

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

/**
 * A frame that contains a panel with drawings
 */
class CreateFrame extends JFrame
{
public CreateFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add panel to frame

CreateComponent component = new CreateComponent();
add(component);
}

public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}

/**
 * A component that displays rectangles and ellipses.
 */
class CreateComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;

// draw a rectangle

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

If you run the code above, you will see a frame that looks like below:

Swing : Displaying Text in a Component

we are going to learn how to add a component into a Frame. This component is going to be pretty straight forward that writes out some text onto the frame.

As a first step, we need to know how to add a component to the frame. The code to add a component to a frame looks like below:

Container contentPane = frame.getContentPane();
Component c = . . .;
contentPane.add(c);

When you add a component to a frame, you are actually adding the component to the frame’s content pane.

Or, you can use a short cut. As of Java SE 5.0, you can simply use the call

frame.add(c);

This will in-turn call the content pane’s add method.

In our case, we want to add a single component to the frame on which we will write out 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/write stuff:
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.

Trivia:
What kind of actions triggers 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 in our Component:

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 "Welcome to Java Swings Tutorial!!!" in our original window, roughly one-quarter 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.

Thus, our paintComponent method will look like this:

class TestPaintComponent extends JComponent {

public void paintComponent(Graphics g) {
g.drawString("Welcome to Java Swings Tutorial!!!", MESSAGE_X, MESSAGE_Y);
}

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

}

Let us now take a look at a fully functional class that will write out some text in our frame:
class TestFrame extends JFrame
{
public TestFrame()
{
setTitle("Print Something");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add panel to frame

TestPaintComponent comp = new TestPaintComponent();
add(comp);
}

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

/**
 * A Component that displays a message.
 */
class TestPaintComponent extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawString("Welcome to Java Swings Tutorial!!!", MESSAGE_X, MESSAGE_Y);
}

public static final int MESSAGE_X = 50;
public static final int MESSAGE_Y = 75;
}


Swing : 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.

The most important methods related to positioning a Frame are:
• 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 etc
• 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

Inheritance Hierarchy of the Frame

In the previous paragraph, I said that because of the inheritance hierarchy of the JFrame class, many of the features of its parent classes are available to it. Before we get any further, if you have any doubts reg. the Java Inheritance concepts, Click Here and refresh your understanding of Inheritance.

The image below explains the inheritance hierarchy of the JFrame and the JPanel classes.

 The Component class (which is the ancestor of all GUI objects) and the Window class (which is the superclass of the Frame class) are the classes that 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.

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 one step.

setBounds(x, y, width, height)

Alternatively, you can give the windowing system control on window placement. If you call
setLocationByPlatform(true);

Before displaying the window, the windowing system picks the location (but not the size), typically with a slight offset from the last window.

Note:
For a frame, the coordinates of the setLocation and setBounds are taken relative to the whole screen. As you will see in the future chapters, for other components inside a container, the measurements are taken relative to the container

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.

Practically speaking, we do not 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;

Nonetheless, we are only bothered as to whether the value we set is displayed fine and the value we get is what is displayed on screen.

There is one exception to this 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

If you don’t explicitly set the size for 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 high-resolution large desktop monitor.

To find out the screen size, use the following steps:

1. 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.)

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

This is a sample code:
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;

3. We use 50% of these values for the frame size, and tell the windowing system to position the frame as follows:

setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);

Additional Tips for dealing with Frames:

Even though we have covered a lot of details about using frames, there are few more tips that will help you deal with these Frames properly.

  • 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 can accomodate 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. We will learn how to do this in future.
  • 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. This will help us position and size our frames to look fine irrespective of the monitor size of your user
  • The GraphicsDevice class also lets you execute your application in full-screen mode.

Sample Code:

Our chapter wouldn't be complete without a code example, or would it?

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

class FirstSizedFrame extends JFrame
{
public FirstSizedFrame()
{
// get screen dimensions
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;

// set frame width, height and let platform pick screen location
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);

// set frame title
setTitle("TestSizedFrame");
}
}

The above is similar to the example in the previous chapter with the following differences:
  1. We have let the frame size to be determined based on the monitor screen size and height
  2. We have set a frame title