Title: Graphics
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

AWT Basics and Swing

AWT stands for Abstract Windowing Toolkit. Most of the notes for a while will contain an import of the package:
import java.awt.*;

The AWT library has been around for a long time and the Java Virtual Machine (JVM) in virtually every browser should understand any Applet written with the AWT library. The AWT library was written to make use of native GUI elements present on each platform where it ran. Consequently, each platform will tend to look a little different due to the fact that the underlying platform is different. Later the Java Sun team decided to create a new GUI library called SWING which was a rewrite this software to be more "bottom up". In otherwords, much less native GUI software was used and most of the software comes from the Java library. You still need to use many components in the AWT library, but SWING provides a more uniform look and feel no matter what platform you are executing on. Here is a list of comparisons between AWT and SWING:

1. Most browsers should have a reasonably up to date version of the JVM (Java Virtual Machine). There was a time when Microsoft was dragging their feet to update JVMs, but those days seem to have passed. However, if you do encounter a browser with an old JVM, you need to either update the browser or use an older version of Java.
2. If you write your Applets for SWING you will use a set of classes that start with "J" and come from:
import javax.swing.*;
The old classes in the AWT are still available, but are somewhat obsoleted by the "J" classes. Here is a table of examples:

SWING class | AWT class
JApplet | Applet
JFrame | Frame
JButton | Button
JComponent | Component
JTextArea | TextArea
JTextField | TextField
JLabel | Label

3. If you encounter some old Java classes that exclusively use the AWT, there are a number of subtle changes which can be annoying in converting AWT work to SWING. Here is a list of some things which I have encountered(you can ignore this list when you start out, but it useful to instructors when converting AWT examples to SWING examples):
  - You can't just call the add routine in JFrame and JApplet. You need to first obtain the Container by calling getContentPane().
  - The default layout manager in a JApplet is BorderLayout instead of FlowLayout.
  - The default text size seems to be larger in Swing than in AWT
  - JTextArea doesn't automatically scroll when all of the rows have been used. There is a way to do it with a JScrollPane class, but it is certainly not compatibale with AWT.
  - In JApplet paint routine doesn't seem to clear the screen before calling paint (note that the Applet class does do this). Not sure if there is an easier solution than explicitly clearing the screen yourself.
4. Swing kept a lot of the original AWT concepts in the areas of dealing with actual drawing, Events (keystrokes, mouse activity), and layout managers. The major area that is impacted is the Component area where SWING provides a different set of classes for buttons, textareas, etc. The following figure gives you a class heirarchy of how AWT and SWING are related:

Concepts

We will want to get some feedback from the GUI (Graphical User Interface). User feedback (i.e. keystrokes, mouse clicks, etc.) comes in the form of Events. Whenever we need events, we will also import from:
import java.awt.event.*;

AWT/Swing supports a number of different Windowing types from Applets, Frames, Windows, Dialogs, etc. We will focus on the concepts that are the same no matter what windowing type you use. We will mostly focus on Frames and Applets. Later sections of the notes will deal with the other windowing types.

Applets are a special window that can live inside of a Browser web page.

GUI Runnable Within a Browser

If you are running in an Applet that lives in a web page, then some of the above steps mentioned for Frame based applications are already done by the Browser. Here is the sequence of events that occur in the Applet case:

1. The browser recognizes some Html applet tags and determines from the Html how many pixels wide and high the applet will take from the phrase width=500 height=150--- see the HelloWorld.html file below.
2. The browser then loads in the java class file based on the code=HelloWorld.class phrase In the HelloWorld.html file below, the browser will download HelloWorld.class from the same directory where HelloWorld.html was found.
3. The browser has a built in Java Runtime Environment (JRE), and will attempt to construct a class named HelloWorld. If the class isn't derived from JApplet or Applet, it won't work.
4. Once the Applet is constructed, the browser calls the Applet init routine to allow the Applet to initialize itself. Often you want to overrid the Applet init routine to do what you want to do here.
5. When the Browser wants the Applet to start executing, it calls the start routine. You may or may not want to override this routine.
6. Whenever it is necessary to paint the screen, the paint routine is called. If you are using higher level components (like the Button class), the paint occurs inside of the higher level component. We will start out with lower level components so the paint routine will be vital to our functionality. When we later move to higher level components, where we won't be seeing the paint method as often.
7. When the user moves onto a different web page, the browser will call the stop routine. You can override the stop routine if you have any special stop code you want to include in your Applet.
8. Unless you override either paint, init or start, you won't have anything worthwhile in your applet.
9. If you want to publish the following Applet, compile it and place HelloWorld.html and HelloWorld.code in some web directory that you own. If you have never published a web page before, the easy approach is to take the following steps:
  - Create a directory called public_html in the your home directory of your Linux account.
  - Place HelloWorld.html and HelloWorld.java in your public_html directory. Compile HelloWorld.java in your public_html directory.
  - Access your web page with the following URL:
http://gettysburg.wccnet.org/~c269xx/HelloWorld.html
10. The second approach you can take on applets is to use the Fake Browser program: appletViewer. Wherever you have HelloWorld.code and HelloWorld.html, issue the command:
appletViewer HelloWorld.html
The appletViewer is an easier environment for debugging Applets.
11. One common problem with publishing web pages and especially Applets is the existence of a very Sticky Cache for applets. This means that you thought you changed the applet, but you still see the old code. You will need to flush the Browser cache --- reload sometimes doesn't work very well for applets. Sometimes you may even need to kill all of your browser windows and reload the applet in a new browser instance. You won't have these problems with the appletviewer.

HelloWorld.java



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

public class HelloWorld extends JApplet {
	public  HelloWorld()
	{
		// optional constructor where you can do you applet initialization
	}
	public void init()
	{
		// optional init routine called at beginning of execution
	}
    public  void paint(Graphics g)
    {
        Dimension d = getSize();
        g.setColor(Color.red);
        g.fillRect(0,0,d.width -1, d.height-1);

        g.setColor(Color.white);
        g.drawString("Hello World", 10,50);


    }//End of Paint
}//End of Applet


HelloWorld.html


<html>
 <head>
<title>HelloWorld.java</title>
</head>
<body>

<applet code="HelloWorld.class" width=500 height=150 >
</applet>

</body></html>


HelloWorld

Note that HelloWorld.class must be in the same directory as the referencing Html file

Running a JFrame from the Command Line

A Frame on the otherhand normally gets started from an application (i.e. java xyz). Our JFrame based applications will always need a main routine where the actual Frame is created. The normal steps for starting up a Frame based application include:

1. Construct the JFrame based class.
2. If you don't want the default layout manager (BorderLayout), you pick your desired Layout Manager. We time on layout managers later.
3. Call the setSize method to set the width and height of the Frame in pixels
4. Add anything you want to the Frame.
5. Make the Frame visible. The default for Frames is invisible. So you typically create your Frame page and then make it visible.

GUI Runnable from the Command line

HelloWorldFrame.java



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

public class HelloWorldFrame extends JFrame {
	public  HelloWorldFrame(String title)
	{
		super(title);
		setSize(600,350);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
    public  void paint(Graphics g)
    {
        Dimension d = getSize();
        g.setColor(Color.red);
        g.fillRect(0,0,d.width -1, d.height-1);

        g.setColor(Color.white);
        g.drawString("Hello World", 10,50);


    }//End of Paint
	 public static void main(String[] args) {
		HelloWorldFrame aFrame = new HelloWorldFrame("My First Frame");
		aFrame.setVisible(true);
	} // end of main
}//End of JFrame


Having Both a JApplet and a JFrame runnable at the command line

I can actually create a java class that can act both as an Applet and can be run from the command line. Try the following code at the command line (i.e. java BasicBoth). Also try out this code as an Applet. The steps are as follows:

1. Create a class derived from JApplet and override the routines desired (i.e. paint, init, start, or stop)
2. Add a main routine that effectively executes the normal steps taken by a browser which are:
3. Create a Window Frame
4. Give the Window Frame a Size in pixels (width, height)
5. Construct the Applet derived class and add it to the window frame.
6. If your code uses an init routine call the init routine
7. If your code uses a start routine call the start routine
8. If your code uses a stop routine, I would recommend that you override the finalize method and call stop from there.

HelloWorldBoth.java

HelloWorld.html



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

public class HelloWorldBoth extends JApplet {
	public  HelloWorldBoth()
	{
		// optional constructor where you can do you applet initialization
	}
	public void init()
	{
		// optional init routine called at beginning of execution
	}
    public  void paint(Graphics g)
    {
        Dimension d = getSize();
        g.setColor(Color.red);
        g.fillRect(0,0,d.width -1, d.height-1);

        g.setColor(Color.white);
        g.drawString("Hello World", 10,50);


    }//End of Paint
	public static void main(String[] args) {
		JFrame aFrame = new JFrame("My First Frame");
		aFrame.setSize(600,350);
		aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	

		// Do the same thing a Browser would do after creating the required JFrame
		HelloWorldBoth applet = new HelloWorldBoth();
		applet.init();
		aFrame.add(applet);
		
		aFrame.setVisible(true);
	} // end of main
}//End of JApplet

Applet Only Characteristics (Applet Life Cycle):

This applet demonstrates the basic Applet life cycle. Look at the Java Console to see the System.out.println stuff. Navigate away from this applet and then navigate back. See if the Applet gets constructed from scratch(I.E.) or we just get a stop followed by a start call (older versions of Netscape). Try this in I.E. and in Netscape.

One feature that is available only to Applets is the getParameter call. This is a way for Applets to get parameters from their Html page. If the parameter doesn't exist, then getParameter returns a null. You can have as many getParameter calls as you want. The applet below has a parameter specified inside the applet tags and it looks like the following:

<applet code=MyApplet.class width=700 height=100>
<PARAM name=myparm value="this is the value of myparm">
</applet>



Just for fun, do a Right click on the top part of the html page associated with the Java Navigator on the left side of my web site and pick view source. You will see heavy usage of the getParameter feature to store the links to a particular web site. By having this applet parametrized, I can reuse the same applet with each of my classes. Of course the set of parameters changes with each class.

Also note the call to showStatus routine. This is also only available for Applets and it writes strings to the status area of a browser (bottom of the screen).

Also Cover this window with another window and then uncover the window and watch the paint count.


//: MyApplet.java
// Shows init(), start() and stop() activities
import java.awt.*;
import javax.swing.*;

public class MyApplet extends JApplet {
  String s;
  int inits = 0;
  int starts = 0;
  int stops = 0;
  int paints=0;
  String myparm = null;
  public MyApplet()
  {
        System.out.println("******MyApplet Constructor");
  }
  public void init()
  {     inits++;
        System.out.println("init called: "+inits);
        myparm = getParameter("myparm");
        System.out.println("myparm = " + myparm);
  }
  public void start()
  {
         starts++;
         System.out.println("start called: "+starts);
  }
  public void stop() {
        stops++;
        System.out.println("stop called: "+ stops);
  }
  public void paint(Graphics g) {
    paints ++;
    s = "inits: " + inits +
      ", starts: " + starts +
      ", stops: " + stops +
      ", paints: " + paints +
      ", myparm = " + myparm;
    g.drawString(s, 10, 10);
    System.out.println("paint called: " + paints);
    showStatus("Painting in MyApplet");
  }
}




Graphics

Useful Drawing Classes/Functions:

- JApplet Class (older Applet class also exists)
  - init()
  - String getParameter(String name)
  - ShowStatus(String) - Display a string in the browser status line
- Color Class
  - Color(float, float, float) - constructor
  - Color(int) - constructor
  - Color(int, int, int) - constructor
  - Constant Colors like Color.red, Color.black, Color.blue, Color.green, Color.yellow, Color.orange, etc. (See online help)
- Font Class
  - Font(String name, int type, int size) - constructor
    - Name possibilities:TimesRoman, Courier, Helvetica, Serif, SansSerif, Monospaced, Dialog
    - type possibilities: Font.BOLD, Font.ITALIC, Font.PLAIN,
    - size is the point size
- FontMetrics Class
  - FontMetrics(Font) - constructor
  - getAscent() -
  - getDescent()
  - getLeading()
  - getHeight()
  - stringWidth(String)
- Graphics Class
  - drawString(String str, int x, int y)
  - drawLine(int x1, int y1, int x2, int y2)
  - drawOval(int x, int y, int width, int height), fillOval(...)
  - drawRect(int x, int y, int width, int height), fillRect(...)
  - drawPolyline(int[] xpts, int[] ypts, int numpts)
  - drawPolygon(int[] xpts, int[] ypts, int numpts), fillPolygon(...)
  - drawRoundRect(int x, int y, int width, int height, int xrounding, int yrounding), fillRoundRect(...)
  - drawArc(int x, int y, int width, int height, int startAngle, int arcAngle), fillArc(...)
  - getColor() returns Color
  - getFont() returns Font
  - getFontMetrics() returns FontMetrics
  - setColor(Color)
  - setFont(Font)
- JComponent Class and Component Class- Note that JApplet, Applet and many other classes are derived from the Component class
  - Dimension getSize() - Dimension.width, and Dimension.height are accessible values
  - Rectangle getBounds() - Rectangle.x, Rectangle.y, Rectange.width, Rectangle.height are accessible values
  - Color getBackground()
  - setBackground(Color)
  - Color getForeground()
  - setForeground(Color)
  - paint(Graphics g)
  - repaint()
- Point - key variables x and y
- Dimension - key variables width and height
- Rectangle - key variables x, y, width, and height
- Polygon - look up in Java API

SimpleObjects.java

SimpleObjects.html


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

public class SimpleObjects extends JApplet {
    public  void paint(Graphics g)
    {
        Dimension d = getSize();
        g.setColor(Color.red);
        g.fillRect(0,0,d.width -1, d.height-1);

        g.setColor(Color.green);
        g.fillOval(0,0, d.width-1, d.height -1);

        g.setColor(Color.blue);
        g.drawLine(0,0, d.width-1, d.height -1);
        g.setColor(Color.white);
        g.drawLine(0, d.height-1, d.width-1, 0);


    }//End of Paint
}//End of Applet


Shapes1.java

Shapes1.html


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

public class Shapes1 extends JApplet {
    final static int maxCharHeight = 15;
    final static Color bg = Color.lightGray;
    final static Color fg = Color.black;

    public  void paint(Graphics g)
    {
        Dimension d = getSize();

        Color fg3D = Color.red;

    // Draw the background.
        g.setColor(bg);
        g.fillRect(0, 0, d.width, d.height);
        g.setColor(fg);

        // drawLine(x1, y1, x2, y2)
        g.drawLine(5, 5,40, 40);

        // drawRect(x, y, w, h)
        g.drawRect(50, 5, 40, 40);

        // draw3DRect(x, y, w, h, raised)
        g.setColor(fg3D);
        g.draw3DRect(100, 5, 40, 40, true);
        g.setColor(fg);

        // drawRoundRect(x, y, w, h, arcw, arch)
        g.drawRoundRect(150, 5, 40, 40, 10, 10);

        // drawOval(x, y, w, h)
        g.drawOval(200, 5, 40, 40);

        // drawArc(x, y, w, h)
        g.drawArc(250, 5, 40, 40, 90, 135);

        // drawPolygon(xPoints, yPoints, numPoints)
        int x1Points[] = {300, 340, 300, 340};
        int y1Points[] = {5, 40, 40, 5};
        g.drawPolygon(x1Points, y1Points, x1Points.length);

        // NEW ROW

        // drawPolyline(xPoints, yPoints, numPoints)
        // Note: drawPolygon would close the polygon.
        int x2Points[] = {5, 45, 5, 45};
        int y2Points[] = {55, 95, 95, 55};
        g.drawPolyline(x2Points, y2Points, x2Points.length);

        // fillRect(x, y, w, h)
        g.fillRect(50, 55, 40, 40);

        // fill3DRect(x, y, w, h, raised)
        g.setColor(fg3D);
        g.fill3DRect(100, 55, 40, 40, true);
        g.setColor(fg);

        // fillRoundRect(x, y, w, h, arcw, arch)
        g.fillRoundRect(150, 55, 40, 40, 10, 10);

        // fillOval(x, y, w, h)
        g.fillOval(200, 55, 40, 40);

        // fillArc(x, y, w, h)
        g.fillArc(250, 55, 40, 40, 90, 135);

        // fillPolygon(xPoints, yPoints, numPoints)
        int x3Points[] = {300, 345, 300, 345};
        int y3Points[] = {55, 95, 95, 55};
        g.fillPolygon(x3Points, y3Points, x3Points.length);
    }//End of Paint
}//End of Applet


DrawSimple.java

DrawSimple.html



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

public class DrawSimple extends JApplet {


    String              param;
    String              version;

public DrawSimple()
{
    version = System.getProperty("java.version");
}

// ---------------------------------------------------------------------------
// Applet init routine
// ---------------------------------------------------------------------------
public void init()
{
    // Read in the parameters from the Html file
       param = getParameter("title");
}// End of Init routine



// ---------------------------------------------------------------------------
public  void paint(Graphics g)
{
        Dimension d = getSize();
        g.setColor(Color.white);
        g.fillRect(0,0,d.width, d.height);

        g.setColor(Color.black);
        g.drawString("First Applet", 10, 50);
        g.drawString(param, 10, 100);
        g.drawString(version, 10, 150);
}//End of Paint



}//End of Applet


TryFonts.java

TryFonts.html



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

public class TryFonts extends JApplet {
    public  void paint(Graphics g)
    {
        Dimension d = getSize();
        g.setColor(Color.white);
        g.fillRect(0,0,d.width, d.height);

        g.setColor(Color.black);
        int yloc = 15;

        Font f = new Font("Serif", Font.PLAIN, 12);
        g.setFont(f);
        g.drawString("Serif Plain 12", 10, yloc);
        yloc += 15;

        f = new Font("SansSerif", Font.PLAIN, 12);
        g.setFont(f);
        g.drawString("SansSerif Plain 12", 10, yloc);
        yloc += 15;

        f = new Font("Monospaced", Font.PLAIN, 12);
        g.setFont(f);
        g.drawString("Monospaced Plain 12", 10, yloc);
        yloc += 15;

        f = new Font("Serif", Font.BOLD, 12);
        g.setFont(f);
        g.drawString("Serif Bold 12", 10, yloc);
        yloc += 15;

        f = new Font("Serif", Font.ITALIC, 12);
        g.setFont(f);
        g.drawString("Serif Italic 12", 10, yloc);
        yloc += 30;

        f = new Font("Serif", Font.ITALIC, 30);
        g.setFont(f);
        g.drawString("Serif Italic 30", 10, yloc);

    }//End of Paint
}//End of Applet


ShowFonts.java

ShowFonts.html


import java.awt.*;
import java.applet.*;

//
// This applet uses the Toolkit class to get a list
// of available fonts, then displays each font in
// PLAIN, BOLD, and ITALIC style.

public class ShowFonts extends Applet
{
   public void paint(Graphics g)
   {
     String fontList[];
     int i;
     int startY;

// Get a list of all available fonts
     fontList = getToolkit().getFontList();

     startY = 15;

     for (i=0; i < fontList.length; i++)
     {
// Set the font to the PLAIN version
        g.setFont(new Font(fontList[i], Font.PLAIN, 12));
        g.drawString("This is the "+ fontList[i]+" font.", 5, startY);
        startY += 15;

// Set the font to the BOLD version
        g.setFont(new Font(fontList[i], Font.BOLD, 12));
        g.drawString("This is the bold "+ fontList[i]+" font.", 5, startY);
        startY += 15;

// Set the font to the ITALIC version
        g.setFont(new Font(fontList[i], Font.ITALIC, 12));
        g.drawString("This is the italic "+ fontList[i]+" font.", 5, startY);
        startY += 20;
     }
   }
}



TextPlacement.java

FontMetrics - Class that contains information about a specific font. This class has stringWidth and getHeight routines which are useful for determining the size of text drawn to the screen. The following gif describes some of the Font size nomenclature.

TextPlacement.html


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

public class TextPlacement extends JApplet {
   public  void paint(Graphics g)
   {
      int titleTextWidth, titleTextHeight;
      int normalTextWidth, normalTextHeight;
      Font                titleFont, normalFont;
      FontMetrics    titleFontMetrics, normalFontMetrics;
      String Corner = "In the corner";
      String title = "Text Placement";

      Dimension d = getSize();

    // Fill in background with the color Red
      g.setColor(Color.red);
      g.fillRect(0,0, d.width, d.height);

    //  Now Fill In the Text

    //Put title in center

      titleFont = new Font("Courier", Font.BOLD, 40);
      titleFontMetrics = getFontMetrics(titleFont);
      titleTextWidth = titleFontMetrics.stringWidth(title) ;
      titleTextHeight=titleFontMetrics.getHeight() ;

      g.setFont(titleFont);
      g.setColor(Color.white); // Text will be white


      g.drawString(title,
          Math.max((d.width - titleTextWidth)/2, 0),
            Math.max((d.height - titleTextHeight)/2, 0) +
                   titleFontMetrics.getMaxAscent() );

    // Fill in the Text for the Corners
      normalFont = new Font("TimesRoman", Font.ITALIC, 14);
      normalFontMetrics = getFontMetrics(normalFont);
      normalTextWidth = normalFontMetrics.stringWidth(Corner);
      normalTextHeight=normalFontMetrics.getHeight();

      g.setFont(normalFont);

// Upper Right Corner
      g.drawString(Corner, d.width - normalTextWidth,
                      normalFontMetrics.getMaxAscent() );

// Lower Right Corner
      g.drawString(Corner, d.width - normalTextWidth,
            getBounds().height -    normalFontMetrics.getMaxDescent() -
                              normalFontMetrics.getLeading());

// See if you can do the Upper Left and Lower Left Corners

   }//End of Paint
}//End of Applet


ImageDisplay.java

This example shows how you can display images in Applets.

ImageDisplay.html

ImageDisplay2.html (Uses Media Tracker Code)


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

public class ImageDisplay extends JApplet
{
    Image player ;

    public void init()
    {
        // getCodeBase() returns the URL where our Html file
        // resides.

        player = getImage(getCodeBase(),"player1.png");
        //
        //  MediaTracker tracker = new MediaTracker(this);
        //  tracker.addImage(player,0);
        //  try { tracker.waitForID(0);}
        //  catch (InterruptedException e) {}
        printSizes();	
    }
    void printSizes()
    {
        System.out.println("Width=" + player.getWidth(null));
        System.out.println("Height=" + player.getHeight(null));
    }

    public void paint(Graphics g)
    {
        g.setColor(getBackground());
        g.fillRect(0,0,getSize().width, getSize().height);

        int ih = player.getHeight(null);
        int iw  = player.getWidth(null);
		
        g.drawImage(player, 0,0, null);

        g.drawImage(player, iw+10,ih+10,iw/2, ih/2, null);
        printSizes();  		
    }
}


player1.png

Exercises:

1. Patriotic Applet
Create an html file and an applet that looks like the following:
Patriotic Applet
Try to make your program adapt to the size of the applet window (i.e. call getSize()). The red and blue sections are the same size. The white area starts at 1/4 of the screen in the x and y coordinates and ends at 3/4 of the screen in the x and y coordinates.
2. Tic Tac Toe Screen
Create an html file and an applet that looks like the following:
TicTacToe
Consider the following starting point


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

public class TicTacToe extends JApplet {

	int MARGIN = 10; //#pixels of margin on all edges of screen
	char player1 = 'x';
	char player2 = 'o';
	int cell_width, cell_height;
	Dimension dimen;
	
	void compute_cell()
	{
		// set dimen and calculate cell_width, and cell_height
	}
	
	int getXLoc(int index)
	{
		// return X coordinate for the start of the X Location index (0, 1, 2)
	}
	int getYLoc(int index)
	{
		// return Y coordinate for the start of the Y Location index (0, 1, 2)
	}
	
	
	void fillCell(Graphics g, char player, int xLocIndex, int yLocIndex)
	{
		// Draw in an Oval in the cell or draw in an X depending on
		//    whether player = player1 or player2
	}
	

	public  void paint(Graphics g)
	{
		compute_cell();
		// fill screen with yellow
		
		// draw tic tac toe starting lines
		
		// call fillCell to draw the appropriate X and O's
		fillCell(g, player1, 1,1);
		fillCell(g, player2, 0,0);
		fillCell(g, player1, 2,2);
		fillCell(g, player2, 0,1);
	}//End of Paint



}//End of Applet
	

3. Modify TextPlacement Example
In the TextPlacement.java example, the upper right and lower right corners were filled with some text.
  - Modify this program to also fill the upper left and lower left corners.
  - Also modify this program to make the text inserted into the corners settable using parameters in the html file.
  - Modify the program so that you color the rectangles that would surround your text with a different color
  - Have the colors be configurable through a parameter. Have the colors specified the way they are on the web:
RGB(Red, Green, Blue) number. For example, Red is 0xFF0000, while blue is 0x0000FF. You probably want to use the version of parseInt that takes 2 parameters.
4. Simple Nested Ellipses
The idea here is to start out simple and incrementally grow into a more complicated applet.
  - Create an ellipse that is filled in with the color red.
  - Using getSize, find out how big your applet is. Using this information make your ellipse expand to the size of the applet.
  - This time create a for loop that successively draws smaller ellipses having the same center. Have the even iterations fill the ellipse with red and and odd iterations fill the ellipse with blue.
5. Draw a checkerboard
6. 2D Button
Create a class that uses draw3DRect to draw a 2D button that has a thickness of more than 1 pixel. Your class should take a color, button thickness, location (x and y), width, height, and whether the button is raised or depressed. If you want more of a challenge, pass in text that will be used to figure out how big the button should be.
HINT:
consider the following code:


for (i=0; i < GC_BUTTON_BORDER_THICKNESS; i++)
{
   g.draw3DRect(x+i, y+i, width - 2*i+1, height - 2*i+1, raised);
}
g.fillRect(x+GC_BUTTON_BORDER_THICKNESS,
           y+GC_BUTTON_BORDER_THICKNESS,
           width -2* GC_BUTTON_BORDER_THICKNESS+2,
           height - 2*GC_BUTTON_BORDER_THICKNESS+2);
	

7. Stick Man
  - Draw a simple stick man. Use drawLine, drawOval (or fillOval) and whatever other Graphics class routines you want. Make the stick man with at least 2 colors.
8. Open Ended Art
Create any art project in an Applet that happens to be of interest to you. You have enough routines to create some pretty good art. Consider the following:
Florida.java


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

public class Florida extends JApplet {
    public void paint(Graphics screen) {
        screen.setColor(Color.white);
        screen.fillRect(0,0,350,350);

        screen.setColor(Color.red);
        screen.drawRect(0,0,349,349);
        screen.drawString("Florida", 185, 75);
        screen.drawLine(185,80,222,80);
        screen.drawRect(2, 2, 345, 345);
        screen.drawRoundRect(182,61,43,24,10,8);
        int x[] = { 10, 234, 253, 261, 344, 336, 295, 259, 205, 211,
            195, 191, 120, 94, 81, 12, 10 };
        int y[] = { 12, 15, 25, 71, 209, 278, 310, 274, 188, 171, 174,
            118, 56, 68, 49, 37, 12 };
        int pts = x.length;
        Polygon poly = new Polygon(x, y, pts);
        screen.drawPolygon(poly);
        screen.fillOval(235,140,15,15);
        screen.fillOval(225,130,15,15);
        screen.fillOval(245,130,15,15);
        for (int ax = 50; ax < 150; ax += 10)
            for (int ay = 120; ay < 320 ; ay += 10)
                screen.drawArc(ax, ay, 10, 10, 0, -180);
    }
}
	

9. Draw a Clock
Create a clock drawing. You can keep it simple with circles and lines. Feel free to use color for the different parts of the clock. You might want to have the colors of the clock configurable by using parameters in the html file.
10. Bar Chart Exercise
  - Make an applet named AChart that provides simple bar chart functionality. Your applet should be driven by input parameters.
  - Put actual numbers on the far right side of each bar to indicate the actual x value represented.
  - Put some labels on the axis. For example, if your bar chart rectangles are horizontal, then on the far left hand side it would be nice to label each bar that is drawn.
11. Line Chart Exercise
Create a Chart applet like the Bar Char exercise above except that you are plotting lines

Last Modified: April 7, 2008 2:40 PM