HW #2 Page
HW#2 --- last modified January 16 2019 00:35:13..
A solution set is posted
here.
Due date: Sept. 26. start of class.
=========
Files to be submitted: cs151hw2file1.java
====================== (Turn in on paper in class your UML diagram.)
Purpose: To play around with Singleton classes, StringTokenizer's, Font's,
======== inheritance, and the awt.
Specification:
==============
For this homework you will modify Digital Clock Applet from Example 3.10.
First you will make it an application that extends JFrame. This
new application reads in a preference file clock.pf then starts up an
analog or digital clock with the preferences as described in this file. Every
30 seconds a randomly chosen fortune is printed at the top of the screen above
the clock. These fortunes come from the file fortunes.
The details of your clock are left reasonably open but here are some
things you must do:
(0) Make a UML diagram for your whole clock.
(1) You should have add a WindowListener to your frame so you can click to
close the frame.
(2) When your application starts, preferences for your clock in
clock.pf should be loaded in with the instance of class
called Preferences which uses the Singleton pattern from the book
(made non public so we can put everything in one file). Anytime,
your application needs a particular preference it gets the information
from this object.
(3) When your application starts the contents of fortunes
are read into the instance of FortuneHandler a class that uses the
Singleton pattern as well. Call this class getFortune() method returns
a randomly chosen fortune from the fortunes in fortune class.
(4) A StringTokenizer is used to parse clock.pf.
The format of clock.pf is:
clocktype:mode:frameXSize:frameYSize:fontName:fontStyle:fontSize
clocktype - has value d or a and says whether the clock is analog or digital.
mode is either 12 or 24 if the clocktype is d and either NumOn or NumOff
if the clocktype is analog.
If the clock is digital 12 means am/pm is printed and numbers less than
12 are used for the hour; 24 means 24 hour time like the book's applet
is used.
If the clock is analog NumOn means numbers appear on the face of the
clock; NumOff means they don't.
frameXsize, frameYSize specify the width and height of the frame in pixels.
fontName - is the name of a java font. For instance, Monospaced.
fontStyle - is either PLAIN, BOLD, or ITALIC.
fontSize - is the size of the font's letters in points.
An example clock.pf is:
a:NumOff:300:200:Sans-serif:BOLD:18
The format of the fortunes file is one fortune per line. For instance,
Man who eats pillow feels down in the mouth.
3^2+4^2=5^2.
Honi soit qui mal y pense.
Below is a short example application (from class) that extends JFrame:
/*
LineDrawer - a simple application to draw a line in a window.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
/**
Run from the command line with a command like:
java LineDrawer filename
This LineDrawer reads in two point from the file filename
and then opens a JFrame where the line given by these points
is drawn.
@author cpollett
@version 1.0
*/
public class LineDrawer extends JFrame
{
public static final int DEFAULT_X_SZ = 400; //dimensions of window
public static final int DEFAULT_Y_SZ = 400;
Polygon line = new Polygon(); // will be used to contain our line
/**
This constructor takes opens the file named name and tries to
read in a line. Background and size of window are also set.
*/
public LineDrawer( String name)
{
super("LineDrawer");
readLine(name);
setSize(DEFAULT_X_SZ, DEFAULT_Y_SZ);
setBackground(Color.black);
}
/**
This method will be called by the run-time system when it wants
to draw the interior of the JFrame.
Since we aren't doing any animation this program directly
overrides paint to draw the line. For animations, a better
way is to add a JPanel to the JFrame and override the
JPanel's paintComponent(Graphics g) method. This avoid flicker.
*/
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawPolygon(line);
}
/*
This functions open the file fileName and tries to read
two Points from it. These Point's are added to the
Polygon line.
*/
private void readLine(String fileName)
{
String mesg = "File did not contain enough points";
Point point = new Point(-1,-1); //we give some dummy values
Point point2 = new Point(-1,-1);//so defined on all syntactic paths
try
{
BufferedReader buf= new BufferedReader(
new FileReader(fileName)
);
//open a Reader for the file fileName
String pt = buf.readLine(); //read in first Point as String
point = parsePoint(pt); //convert String to Point
String pt2 = buf.readLine(); //now do the same for second point
point2 = parsePoint(pt2);
buf.close();
}
catch(FileNotFoundException fe)
{
System.err.println("File not found");
System.exit(1);
}
catch(IOException ie)
{
System.err.println("An I/O Exception occurred:"+ie.toString());
System.exit(1);
}
catch(Exception ee)
{
System.err.println(mesg);
System.exit(1);
}
line.addPoint(point.x, point.y);
line.addPoint(point2.x, point2.y);
}
/*
This function takes a String and tries to determins a Point
object from it.
The idea is a String like:
10,20
is supposed to represent the point (10,20).
*/
private Point parsePoint(String pt)
throws Exception /* we have learned how to define our
own exceptions yet so I just throw an Exception
*/
{
int x=-1; //dummy values so defined on all syntactic paths.
int y=-1;
StringTokenizer tokens = new StringTokenizer(pt,",");
if(tokens.hasMoreTokens()) //get first coordinate
{
x = Integer.parseInt(tokens.nextToken());
}
else
throw new Exception();
if(tokens.hasMoreTokens()) //get second coordinate
{
y = Integer.parseInt(tokens.nextToken());
}
else
throw new Exception();
return new Point(x,y);
}
// Main entry point
public static void main(String[] args)
{
if( args.length == 0 )
{
System.err.println("You need to give as a comand line "+
"argument an point file.");
System.exit(1);
}
LineDrawer app= new LineDrawer(args[0]);
app.show(); //show the JFrame on the screen
app.addWindowListener( /* handle close window events with
this anonymous inner class
*/
new WindowAdapter()
{
public void windowClosing( WindowEvent e)
{
System.exit(0);
}
}
);
}
}
//End of LineDrawer
Here is the code from Jia's book for the DigitalClock applet.
Notice his applet's time flickers.
import java.awt.*;
import java.util.Calendar;
public class DigitalClock extends java.applet.Applet implements Runnable
//means has a run() method.
{
protected Thread clockThread = null;
protected Font font = new Font("Monospaced", Font.BOLD, 48);
protected Color color = Color.green;
public void start()
{
if(clockThread == null)
{
clockThread = new Thread(this);
//uses this class' run method
clockThread.start();
}
}
public void stop()
{
clockThread=null;
}
public void run()
{
while(Thread.currentThread() == clockThread)
{
repaint();
try
{
Thread.currentThread().sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g) //called by browser when wants to redraw
{
Calendar calendar= Calendar.getInstance(); //is Singleton
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
g.setFont(font);
g.setColor(color);
g.drawString(hour + ":" + minute/10 + minute % 10
+ ":" + second/10 + second % 10,
10, 60
);
}
}
Point Breakdown
===============
UML Diagram describing your clock.....1pt
Department Java Coding guidelines
followed...........................1pt
Both Preferences class and
FortuneHandler class use
Singleton pattern..............1pt
clock.pf and fortunes files read
correctly..........................1pt
These files are parsed using
Stringtokenizer.....................1pt
A digital clock will appear with correct
font and 12 or 24 time if the
preferences so demand...............1pt
An analog clock will appear with
or without numbers on the face of the
clock as the preferences demand.....1pt
Every 30 sec a random fortune is
gotten from the FortuneHandler
and drawn to the screen.............1pt
Total.................................8pts
The most creative and original clock will
get 1 additional bonus point which will be
added to that person's score for the semester
after final curving has been done.
A solution set is posted
here.
|