Creating Java Classes

We've already seen how to create classes in a rudimentary way: You need to create a class to do anything at all, as when we created the main class for the applications we've built:

 public class ch10_01  {     public static void main(String[] args)     {         System.out.println("Welcome to Java");     } } 

In preparation for the next chapter, let's take a look at a more advanced example. In this case, I'll create a new class named AppFrame based on the Java Frame class. This class is what you use to create frame windows (a frame window has a frame including a border and title bar) in Java.

Here's what it will look like in the main method. I'll create a new object named f of the AppFrame class, passing the text we want to appear in that window to that class's constructor:

 public class ch10_14  {    public static void main(String argv[]) {  AppFrame f = new AppFrame("Creating windowed Java applications...");  .         .         .    } } 

Because the AppFrame class is built on the Java Frame class, I can use the Frame class's setSize method to give this new window a size of 400 x 200 pixels. I can use the show method to display it onscreen:

 public class ch10_14  {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");  f.setSize(400, 200);   f.show();  } } 

Creating New Classes

The AppFrame class is based on the Java Frame class, which means that AppFrame has all the built-in Frame class's methods. You can find those methods in Table 10-2.

Table 10-2. Methods of the Frame Class
Methods Does This
void addNotify() Allows this frame to be displayed by connecting it to a native screen resource
protected void finalize() Called when the frame is about to be disposed of
int getCursorType() Replaced by Component.getCursor()
int getExtendedState() Gets the state of this frame
static Frame[] getFrames() Returns an array containing all frames created by the application
Image getIconImage() Returns the image to be displayed in the minimized icon
Rectangle getMaximizedBounds() Gets maximized bounds for this frame
MenuBar getMenuBar() Returns the menu bar
int getState() Returns the current state of the frame
String getTitle() Returns the frame's title
boolean isResizable() Sets whether this frame is resizable by the user
boolean isUndecorated() Indicates whether this frame is undecorated
protected String paramString() Returns the parameter string of this frame
void remove(MenuComponent m) Removes the given menu bar from this frame
void removeNotify() Makes this frame undisplayable
void setCursor(int cursorType) Replaced by Component.setCursor(Cursor)
void setExtendedState(int state) Sets the state of this frame
void setIconImage(Image image) Sets the image to display in the minimized icon for this frame
void setMaximizedBounds(Rectangle bounds) Sets maximized bounds for this frame
void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the specified menu bar
void setResizable(boolean resizable) Sets whether this frame is resizable by the user
void setState(int state) Sets the state of this frame
void setTitle(String title) Sets the title for this frame to the given string
void setUndecorated(boolean undecorated) Disables or enables decorations for this frame

You can create your own classes with the class statement in Java, as we've seen. The AppFrame class is built on the Frame class, which in object-oriented terms means that AppFrame inherits the Frame class. To indicate that you want one class to be based on another, you use the extends keyword like this (note that I'm not using an access specifier when defining AppFrame , which means this class will use the default access specifier, which is private ):

 import java.awt.*;  public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } }  class AppFrame extends Frame   {   .   .   .   }  

Note also that the Java Frame class is part of the Java Abstract Windowing Toolkit (AWT) package. That means that I must import this package with the statement import java.awt.*; .

Creating a Constructor

This new class needs a constructor because I want to pass the text that the window should display to that constructor. You create a constructor simply by creating a method in a class that has the same name as the class. In this case, that's AppFrame (constructors do not specify any return value):

 import java.awt.*;  import java.awt.event.*; public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;  public AppFrame(String text)   {   .   .   .   }  } 

AppFrame

You might note that the methods I'm adding to the AppFrame class are not declared static . That's because these methods will be used only as part of an object, not as class methods. In particular, I create an object of the AppFrame class named f in the main method and then use the methods of that object.

I'll store the text passed to the constructor in a string named displayText , this way:

 import java.awt.*;  import java.awt.event.*; public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {  String displayText;   public AppFrame(String text)   {   displayText = text;   }  } 

Using Graphics Objects

The next step is to display the text in the window itself. The Frame class has a method named paint that is automatically called whenever the window needs to be drawn on the screen. This method is passed an object of the Java Graphics class, which I will call g :

 import java.awt.*;  import java.awt.event.*; public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }  public void paint(Graphics g)   {   .   .   .   }  } 

You can use the Graphics object's methods to draw in a window, and you'll find a selection of those methods in Table 10-3. With the methods declared with the abstract keyword, you must base your own class on the Graphics class before using those methods (we won't use abstract methods in this book).

Table 10-3. Methods of the Graphics Class
Method Does This
abstract void clearRect(int x, int y, int width, int height) Clears a rectangle (fills it with the background color )
abstract void clipRect(int x, int y, int width, int height) Clips a rectangle
abstract void copyArea(int x, int y, int width, int height, int dx, int dy) Copies an area of size dx and dy
abstract Graphics create() Creates a new Graphics object and makes it a copy of the current one
Graphics create(int x, int y, int width, int height) Creates a new Graphics object, with a new translation and clip area
abstract void dispose() Disposes of a graphics context
void draw3DRect(int x, int y, int width, int height, boolean raised) Displays a 3D rectangle
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws a circular or elliptical arc
void drawBytes(byte[] data, int offset, int length, int x, int y) Draws the text stored in the byte array
void drawChars(char[] data, int offset, int length, int x, int y) Draws the text stored in the character array
abstract boolean drawImage(Image img, int x, int y, Color bgcolor , ImageObserver observer) Draws as much of the specified image as possible
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) Draws as much of the given image as possible
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) Draws as much of the image as can fit inside the rectangle
abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) Draws as much of the given image as has been scaled to fit inside the rectangle
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws as much of the image as possible, scaling it to fit inside the given area
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Draws as much of the area of the image as possible, scaling it to fit inside the given area of the destination surface
abstract void drawLine(int x1, int y1, int x2,int y2) Draws a line, in the current default color between the points ( x1 , y1 ) and ( x2 , y2 )
abstract void drawOval(int x, int y, int width, int height) Draws the outline of an oval
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon with vertices defined by the x and y coordinate arrays
void drawPolygon(Polygon p) Draws a polygon defined by the given Polygon object
abstract void drawPolyline(int[] xPoints, int[] yPoints,int nPoints) Draws a sequence of connected lines
void drawRect(int x, int y, int width, int height) Draws the specified rectangle
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws a round-cornered rectangle
abstract void drawString(AttributedCharacterIterator iterator, int x, int y) Draws the text given by the iterator
abstract void drawString(String str, int x, int y) Draws the text given by the string
void fill3DRect(int x, int y, int width, int height, boolean raised) Paints a filled 3D rectangle
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc
abstract void fillOval(int x, int y, int width,int height) Fills an oval bounded by the given rectangle
abstract void fillPolygon(int[] xPoints, int[] yPoints,int nPoints) Fills a closed polygon defined by arrays of x and y coordinates
void fillPolygon(Polygon p) Fills the polygon defined by the Polygon object with the current color
abstract void fillRect(int x, int y, int width, int height) Fills the specified rectangle
abstract void fillRoundRect(int x, int y, int width,int height, int arcWidth,int arcHeight) Fills a rounded corner rectangle
void finalize() Called when the object is about to be disposed of
abstract Shape getClip() Returns the clipping area
abstract Rectangle getClipBounds() Returns the bounding rectangle of the clipping area
Rectangle getClipBounds(Rectangle r) Returns the bounding rectangle of the clipping area
Rectangle getClipRect() Replaced by getClipBounds()
abstract Color getColor() Returns this graphics context's current foreground color
abstract Font getFont() Returns the current font
FontMetrics getFontMetrics() Returns the font metrics of the font
abstract FontMetrics getFontMetrics(Font f) Returns the font metrics for the given font
boolean hitClip(int x, int y, int width, int height) True if the given area intersects the rectangle of the clipping area
abstract void setClip(int x, int y, int width, int height) Sets the current clip to the given rectangle
abstract void setClip(Shape clip) Sets the clipping area to a shape
abstract void setColor(Color c) Sets the graphics context's foreground color
abstract void setFont(Font font) Sets the graphics context's font.
abstract void setPaintMode() Sets the paint mode
abstract void setXORMode(Color c1) Sets the paint mode to use XOR painting
String toString() Returns a String object that represents the Graphics object
abstract void translate(int x, int y) Translates the origin of the graphics context to a new origin

In this case, I'll use the drawString method to display the text in the window, like this:

 import java.awt.*;  import java.awt.event.*; public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }     public void paint(Graphics g)     {  g.drawString(displayText, 60, 100);  } } 

Closing Application Windows

There's one more refinement to make. When the user clicks the Close button at the upper right in the window we're creating, we'll need to handle the window-closing event that occurs. To handle events in Java, you use an event listener. In this case, I'll use an event listener to catch the window-closing event and, when that event occurs, end the program using the call System.exit(0); . This call ends the program and passes a value of (which indicates normal termination) as an exit code to the operating system.

Handling Java events in detail is beyond the scope of this book, but here's how it works here. In this case, I'll add a window listener to the AppFrame object that will "listen" for window-closing events and, when one occurs, end the program. Note that to handle events with AWT objects, you must import the classes in the java.awt.event package:

Listing ch10_14.java
 import java.awt.*;  import java.awt.event.*;  public class ch10_14 {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications...");        f.setSize(400, 200);  f.addWindowListener(new WindowAdapter() {public void   windowClosing(WindowEvent e) {System.exit(0);}});  f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }     public void paint(Graphics g)     {         g.drawString(displayText, 60, 100);     } } 

You can see the results of this code in Figure 10-2. When you start this application, the window appears, displaying the text as shown.

Figure 10-2. Running a windowed Java application.

graphics/10fig02.gif

Now that we're in the Java business, it's time to put all this technology to work with XML. I'll do that in the next chapter.



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net