Tuesday, May 31, 2011

Basics of Event Handling

In the previous chapters, we had seen how to create various Swing UI components. What good is a UI component that cannot handle user actions? Lets say you want to open a pop up when the user clicks a button or you want to save some data user entered in the screen when he clicks save, how would you do it?

Event Handling is your answer. Each of the two examples mentioned above are user stimulated events and using event handling, we can handle the events and take appropriate action.

The next thing your mind says is, what is event handling? Right??

Well, that is exactly what we are going to learn in this and the next few chapters.

So, lets get started!!!

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.

ActionListener listener = . . .;
JButton button = new JButton("Ok");
button.addActionListener(listener);

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.

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.*;

/**
* @version 1.1 31-May-2011
* @author Anand Vijayakumar
*/
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:



Prev: Displaying Images

Next: Creating Listeners Containing a Single Method Call

Friday, May 27, 2011

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.*;

/**
* @version 1.1 25-May-2011
* @author Anand Vijayakumar
*/
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\\lillies.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;
}


If you place the image in the right path and then execute this class you will get a screen like below:



Prev: Using Special Fonts

Next: Basics of Event Handling

Using Special Fonts for Text

In almost all cases, your UI program will display text that will be read by the user using it. And hence, it would be nice if we can set some good looking fonts instead of the dull/default fonts. This is what we are going to learn in this chapter.

So, lets get started!!!

Using Special Fonts:

Remember the chapter on displaying components in a frame? We displayed some text inside of our frame. But, the font used there was the default font. You can always show text in a different font which you like. You can specify a font by using the “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.”

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.*;

/**
* @version 1.1 25-May-2011
* @author Anand Vijayakumar
*/
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);
}
}


If you execute the code above you will an output like below:


As you can see, to show that the positioning is accurate, the sample program also draws the baseline and the bounding rectangle.

Prev: Using Colors

Next: Displaying Images

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

Prev: Creating a 2D Shape

Next: Using Special Fonts for Text

Creating 2-Dimensional Shapes

In the previous chapters, we learnt how to create an empty frame and also writing out some stuff on it. The next step in creating UI components with Swing is to start drawing 2 dimensional shapes like lines, rectangles, circles and so on. This is what we are going to learn in this chapter.

So, lets get started!!!

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

Code:

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

/**
* @version 1.0 25-May-2011
* @author Anand Vijayakumar
*/
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:




Prev: Displaying Text in a Component

Next: Using Colors

Displaying Text in a Component

In the previous chapters, we learnt how to create a frame and then how to size and position it. The next step is to start putting stuff inside a frame. Seeing empty frames is kind of boring, isnt it…

So, lets get started!!!

Displaying Information in a Frame

In this chapter, 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:


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

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
public class PrintSomethingInFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

/**
* A frame that contains a message panel
*/
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;
}


If you run this class you will see something like below:


Prev: Positioning a Frame

Next: Creating 2D Shapes

Tuesday, May 24, 2011

Positioning a Frame

In the previous chapter, we learnt how to create a simple frame. Now, let us take a look at how we can position the frame in the screen.

So, lets get started!!!

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?

Code:

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

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
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

If you run this code you will get an output like below:



Prev: Creating a Frame

Next: Displaying Text in a Component

Creating a Frame

Now that we know the history of Java Swings, lets get down to business. The first thing we are going to learn is “How to create a Frame”

So, lets get started!!

What is Frame?

A top-level window (i.e., 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.

Trivia:
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 behavioural inconsistencies.

How would a Frame Look?

An empty or a simple frame will look like below:


Don't lose heart. This frame practically has no components in it. It is just a simple window that we have created with no components or fields in it.

What is the code to generate this Frame?


The code is pretty straight forward and is available below:
import java.awt.*;
import javax.swing.*;

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
public class MyFirstFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
FirstFrame frame = new FirstFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class FirstFrame extends JFrame
{
public FirstFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}


If you are new to swings, don't lose heart just yet. I am not going to leave you all by yourself to figure this out. Lets go through this code line by line.

The first lines are the import statements. 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 FirstFrame whose constructor sets the size to 300 × 200 pixels. This is the only difference between a FirstFrame and a JFrame. (We have set a size instead of 0 X 0)

In the main method of the Test class, we construct a FirstFrame object and make it visible.
There are two technical issues that we need to address in every Swing program.

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

I know that, this is too much to swallow in one bite, but stay with me here. For now just think of this as a magic wand that is used to start your Swing program. We will get into the details in the subsequent chapters.

Next, we define what should happen when the user closes the application’s frame. Since this is our first simple example, we just want to exit when the user clicks the close icon ‘X’. To make this happen, 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.

Trivia:
I know that it is kind of surprising that the program doesn't terminate when the user clicks the close icon. Unfortunately that is how Swing works and we have to manually write the code to exit.

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.

Did you notice something Surprising?

If you havent yet run the code I pasted above, I suggest you do it in order to be surprised.
Did you see that, even though the code in the main method has completed execution, the frame is still visible? This is unlike regular java programs that exit once the main method is done executing.

The reason is that, the event dispatch thread keeps the program alive until it is terminated, either by closing the frame or by calling the System.exit method.

Prev: Introduction to Java Swings

Next: Positioning a Frame

Introduction to Java Swings

Well, finally I have begun writing articles for these topics on Advanced Java Concepts. We begin with the first part, which is UI Programming with Java Swings. This chapter is just an introduction to this great technology.

So, lets get started!!!

Before Java Swings – Abstract Window Toolkit (AWT)

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). For example, if you used the original AWT to put a text box on a Java window, an underlying “peer” text box actually handled the text input. 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.”

The peer-based approach worked well for simple applications, but it soon became apparent that it was pretty difficult to write a high-quality portable graphics programs that depended on native user interface elements. User interface elements such as menus, scrollbars, and text fields can have subtle differences in behavior on different platforms. It was hard, therefore, to give users a consistent and most importantly a predictable experience with this approach. Moreover, some graphical environments (such as X11/Motif) do not have as rich a collection of user interface components when compared to Windows or the Mac. This further limits a portable library based on peers to a “lowest common denominator” approach. As a result, GUI applications built with the AWT simply did not look as nice as native Windows or Macintosh applications, nor did they have the kind of functionality that users of those platforms wanted or expected.

The nail on the coffin was the fact that, the code did not just work the same way in different platforms. Unfortunately developers were forced to test out their code in the different platforms before they could release them, effectively killing the motto of Write Once, Run Anywhere.

Birth of Swings from Netscape IFC

In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes) that used a totally different approach. User interface elements, such as buttons, menus, and so on, were painted onto blank windows. The only functionality required from the underlying windowing system was a way to put up windows and to paint on the window. Thus, Netscape’s IFC widgets looked and behaved the same no matter which platform the program ran on. Sun worked with Netscape to perfect this approach, creating a user interface library with the code name “Swing.” Swing was available as an extension to Java 1.1 and became a part of the standard library in Java SE 1.2.

Note
Swing is not a complete replacement for the AWT—it is built on top of the AWT architecture. Swing simply gives you more capable user interface components.

Of course, Swing-based user interface elements will be somewhat slower to appear on the user’s screen than the peer-based components used by the AWT. The point here is that, given the processing power of the modern computers, this shouldn't be a problem at all.

Why Java Swings?

Even though AWT is powerful, there are many compelling reasons as to why Swings is a more successful and preferred choice for UI programmers. They are:

1. Swing has a rich and convenient set of user interface elements.
2. Swing has few dependencies on the underlying platform. This means that it is less prone to platform-specific bugs.
3. Swing gives a consistent user experience across platforms.

But, the third advantage is also a potential drawback. If the UI 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.

Swing solves this problem in a very elegant way. Programmers writing Swing programs can give the program a specific “look and feel.” This way, the users using the system wouldn't be confused by the look and feel of the system.

Next: Creating a Frame

Tuesday, May 3, 2011

J2EE Design Patterns - Interview Questions

The following are some questions that you might encounter when you face an Interview for a position of a Senior Java/J2EE Developer. Design Patterns are very exciting and useful and most managers expect their developers to have a sound understanding of the most important patterns.

Also, as part of my series of chapters on the SCWCD Certification Series, there were a few articles posted on Design Patterns. You can use them to revise/understand these patterns better.

They are:

Introduction to Design Patterns
Elements of a Design Pattern
Value Object Pattern
DAO Pattern
Business Delegate Pattern
MVC Pattern
Front Controller Pattern


Questions:


What are design patterns?


A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs time and again in our environment, and describes its solution to this problem in such a way that we can use this solution any number of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.

Can we always apply the same solution to different problems at hand?

No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.

What should be the level of detail/abstraction which should be provided by a design pattern?

Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns. The details of implementation are usually upto the developer who is coding at the ground level.

What are the most common problems which one faces during the application design phase that are solved by design patterns?

Some are:

1. Identifying components, internal structures of the components, and relationships between components.
2. Determining component granularity and appropriate interactions
3. Defining component interfaces.

How does one decide which Design pattern to use in our application?

We need to follow these steps:

1. We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns.
2. Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use.
3. Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients).


What is Refactoring?

Learning different design patterns is not sufficient to becoming a good designer. We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.

What are Antipatterns?

Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions. This helps others by preventing them from repeating these mistakes in their applications. Such documented mistakes are called antipatterns.

As we do development in tiers, how do we divide patterns in tiers?

The Sun Java Center has classified the patterns in three tiers. These are:

Presentation tier patterns for web-component tier,
Business tier patterns for business logic (EJB) tier, and
Integration tier patterns for connection to the databases.

What are the Presentation Tier Patterns?

The presentation tier patterns are:

Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.

What are the Business Tier Patterns?

The business tier patterns are:

Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.

What are the Integration Tier Patterns?

Integration tier patterns are:

Data Access Object (DAO) and Service Activator

What is Intercepting Filter pattern?

Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.

What is Front Controller pattern?

It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.

What is View Helper pattern?

There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.

What is Composite View pattern?

This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.

What is Service to Worker pattern?

This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.

What is Dispatcher View pattern?

This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.

What is Business Delegate pattern?

This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.

What is Value Object pattern?

Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation

What is Session Façade pattern?

This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.

What is Value Object Assembler pattern?

This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.

What is Value List Handler pattern?

This pattern provides a sound solution for query execution and results processing.

What is Service Locator pattern?

It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.

What is Data Access Object pattern?

It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.

What is EJB Command pattern?

Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.

What is Version Number pattern?

This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.

What all patterns are used to improve performance and scalability of the application?

Value Object, Session Façade, Business Delegate and Service Locator.

What design patterns could be used to manage security?

Single Access Point, Check point and Role patterns



If you have any more questions on Design Patterns that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers