Frequently
Asked Questions for CS410X-LIST and CS411X-LIST
1.
AWT Questions
1.1
Image Questions
¥ How
do I convert 3 short arrays, r, g and b into an image?
¥ How
do I build an image in memory?
¥ How
do I load an Image?
¥ How
do I place a component on a background image?
¥ How
to display an image (sequence)?
¥ How
do I grab a frame?
¥ How
do I convert from pict to image?
¥ how
do I time image processing?
1.2
Graphics Questions
¥ How
do I find the screen size and resolution?
¥ How
do I nest layouts in panels?
¥ How
do I use Gridbag Layout?
¥ How
do I use grid layout?
¥ How
do I add a couple of panels to a frame?
¥ How
do I intersect a ray with an ellipse?
¥ How
do I intersect a ray with an ellipse (Code Example)?
¥ How
do I nest layouts in panels?
¥ How
do I draw Points in 3D in Java?
1.3
Event Questions
¥ How
do I move Components?
¥ How
do I move Components (Code Example)?
¥ How
do I use movable components in an interface?
¥ How
do I set the location of a component?
1.4
Other AWT Questions
¥ How
do you account for PEER classes?
¥ How
do I put a gui on my stock quotes?
2.
File IO Questions
¥ How
do I process a line at a time?
¥ How
do I build a custom streamtokenizer?
¥ How
should I save to a file?
¥ How
do I read and write gzipped objects with java?
¥ How
do I display a directory?
¥ How
to I read and Write a gzipped file of floats?
¥ How
do I set the pict file type?
¥ How
do I buffer output in Java?
¥ How
do I copy a file in Java?
3.
NET Questions
¥ How
do I send e-mail in Java?
¥ How
do I get an a name from an IP address in Java?
¥ How
do I check my mail with Java?
¥ How
do I get an address from a name in Java?
¥ How
do I do a client server with sockets in Java?
¥ How
do I build servelets in Java?
4.
Keyboard Input Questions
¥ How
do I make a system console?
¥ How
do I parse a string?
¥ How
do I convert a string to an int?
¥ How
do I build a command line Interpreter?
¥ How
do you determine a key-code?
¥ How
do I figure out what modifiers are pressed?
¥ How
can I obtain a consistent keyboard mapping?
¥ How
can I print all the key-event info?
¥ How
do I drive a serial line-based controller?
5.
Threads Questions
¥ How
do you set alarms in Java?
¥ How
do I do implicit threading?
6.
Util Questions
¥ How
do I get Stockquotes in Java?
7.
Multimedia Questions
¥ How
do I play notes in Java?
¥ How
do I capture a video sequence?
¥ How
do I set the flags to grab a frame?
¥ How
do I get a printed copy of QT-Components?
¥ how
do I get QT4Java?
¥ How
do I learn about digitizing video?
7.
Miscellaneous Questions
¥ How
do I get the methods from a class?
¥ How
do I write help?
¥ How
do I add meta tags?
¥ How
do I use a jar file?
¥ How
do I serialize an object?
¥ How
do I unsubscribe?
¥ How
do I set up for browsing?
¥ How
do I make a Jar file from many directories?
¥ How
do I tell the type of an object?
¥ How
do I hand in Late homework?
¥ How
do I get the author tag in JavaDoc?
¥ How
do I find javadoc?
¥ How
do I know if a class can be public?
¥ How
do I make Javadoc work on non-public files?
¥ How
do I draw BNF Diagrams?
¥ How
do you uncompress a Jar file?
¥ How
do I run an application with codewarrior?
¥ How
do I add jars to my class path?
¥ How
do I compile diffcad?
¥ How
do I pack an Array of bytes?
¥ How
do I playback quicktime movies in Java?
¥ How
do I set the com port?
¥ How
do I install Java programs on Solaris/win95/winnt?
¥ How
do I update codewarrior?
¥ How
do I add features to a class?
¥ How
do I find Kahindu?
¥ How
do I get tech-support from Metrowerks?
¥ How
do I run Java using CGI?
¥ How
do I design my programs?
¥ How
do I describe a problem to get help?
¥ How
do you run a makefile?
¥ How
do I install Java3D?
¥ How
will I earn a grade in Embedded Control?
¥ How
do I install the COMM API on NT?
¥ How
do I run quick-time for Java, under windows?
How
do I convert 3 short arrays, r, g and b into an image?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I convert 3 short arrays, r, g and b into an image?
Date:
Wed, 4 Nov 1998 15:57:18 -0400
public
Image short2Image(short r[][],short g[][], short b[][]) {
int width = r.length;
int height = r[0].length;
Toolkit tk = Toolkit.getDefaultToolkit();
int pels[] = new int[width*height];
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++) {
pels[ x + y * width] =
0xff000000
| (r[x][y] << 16)
| (g[x][y] << 8)
| b[x][y];
}
return tk.createImage(
new MemoryImageSource(
width,
height,
ColorModel.getRGBdefault(),
pels, 0,
width));
}
How
do I build an image in memory?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I build an image in memory?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
import
java.awt.*;
import
java.awt.image.*;
public
class MemImage extends java.applet.Applet
{
Image i;
int pixel[]; // The memory array, one int is one pel.
int w=300; // Image width and height in pels
int h=200;
int RED=0xffff0000; // Some typical pel values
int GREEN=0xff00ff00;
int BLUE=0xff0000ff;
int BLACK=0xff000000;
public
void init()
{
pixel=new int[h*w];
for(int i=0;i<h;i++)
for(int j=0;j<w;j++)
if(i==0 || j==0 || i==h-1 || j==w-1)
pixel[w*i+j]=BLACK; // Draw a border
else if(j<100)pixel[w*i+j]=RED;
else if(j<200)pixel[w*i+j]=GREEN;
else pixel[w*i+j]=BLUE;
i=createImage(new MemoryImageSource(w,h,pixel,0,w));
}
public
void paint(Graphics g)
{
g.drawImage(i,50,50,this);
}
}
How
do I load an Image
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I load an Image
Date:
Sun, 22 Nov 1998 09:47:29 -0400
import
java.awt.*;
class
LoadImage extends Frame
{
Image i;
// Images are loaded asynchronously - you need a tracker to know
when
complete
MediaTracker tracker;
LoadImage()
{
super("LoadImage");
i=Toolkit.getDefaultToolkit().getImage("background.gif");
tracker = new MediaTracker(this);
tracker.addImage(i,0);
// ... do other useful work here ...
try{tracker.waitForID(0);}catch(Exception e){}
setBackground(Color.red);
reshape(0,0,180,180);
show();
}
static
public void main(String args[]) { new LoadImage(); }
public
boolean handleEvent(Event e)
{
if(e.id==Event.WINDOW_DESTROY)System.exit(0);
return(super.handleEvent(e));
}
public
void paint(Graphics g)
{
g.drawImage(i,50,50,this);
}
}
How
do I place a component on a background image?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I place a component on a background image?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
import
java.awt.*;
public
class Background extends Frame
{
Image
background=Toolkit.getDefaultToolkit().getImage("background.gif");
//
If running as an applet use the following instead
//
Image background=getImage(getCodeBase(),"background.gif");
ImagePanel p;
Button b=new Button("Press");
Background()
{
super("Background");
setLayout(new FlowLayout());
reshape(0,0,150,150);
MediaTracker tracker=new MediaTracker(this);
tracker.addImage(background,0);
try{tracker.waitForID(0);}catch(Exception e){}
p=new ImagePanel(background);
p.add(b);
add(p);
Thread.yield();
show();
}
public
boolean handleEvent(Event e)
{
if(e.id==Event.WINDOW_DESTROY)
System.exit(0);
show();
return(super.handleEvent(e));
}
public
static void main(String args[]){new Background();}
}
class
ImagePanel extends Panel
{
Image background;
Dimension d=new Dimension();
ImagePanel(Image
b)
{
background=b;
d.width=background.getWidth(null);
d.height=background.getHeight(null);
d.width=80;
d.height=80;
}
public
Dimension preferredSize()
{
return(d);
}
public
void paint (Graphics g)
{
g.drawImage(background,0,0,null);
g.drawRect(0,0,d.width-1,d.height-1);
}
}
how
do I find the screen size and resolution?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
how do I find the screen size and resolution?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
import
java.awt.*;
public
class Screen extends java.applet.Applet
{
public
void init()
{
Toolkit t=Toolkit.getDefaultToolkit();
add(new Label("Dots per inch is "+t.getScreenResolution()));
add(new Label("Screen size is "+t.getScreenSize()));
}
}
How
do I process a line at a time?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I process a line at a time?
Date:
Wed, 11 Nov 1998 16:50:20 -0400
To
process one line of text at a time, look at:
public static void processJava() {
FileInputStream fis = getFileInputStream();
String line;
DataInputStream dis = new DataInputStream(fis);
System.out.println("<HTML><BODY><PRE>");
try { while ((line = dis.readLine()) != null)
System.out.println(line);
}
catch (IOException e) {
System.out.println("Futil: ER! in processJava");
}
System.out.println("</PRE></BODY></HTML>");
closeInputStream(fis);
}
See
how readLine returns a string? This enables you to
scan
a document for entire words. How would you
read
a statement in Java at a time?
Would
you use a streamtokenizer? How would you set
the
syntax?
Look
Futil.java over very carefully!!
Please
feel free to ask questions.
Regards,
- DL
--------
Futil.java follows:
package
futils;
import
java.util.*;
import
java.awt.*;
import
java.io.*;
public
final class Futil {
/**
* Don't let anyone instantiate this class.
*/
private Futil() {}
public static String getReadFileName() {
Frame frm = new Frame();
frm.setSize(100,100);
FileDialog dialog = new FileDialog(frm, "select file");
dialog.show();
String file_name = dialog.getFile();
String path_name = dialog.getDirectory();
String file_string = path_name + file_name;
System.out.println("Opening file: "+file_string);
dialog.dispose();
return file_string;
}
public static FileOutputStream getWriteFileOutputStream() {
try {
return
new FileOutputStream(getWriteFileName());
}
catch (Exception e) {
System.out.println("Er: FileOutputStream in futils.java");}
return null;
}
public static String getWriteFileName() {
FileDialog dialog = new FileDialog(new Frame(), "Enter file
name",FileDialog.SAVE);
dialog.show();
String fs = dialog.getDirectory() + dialog.getFile();
System.out.println("Opening file: "+fs);
dialog.dispose();
return FilterFileNameBug(fs);
}
public static String getWriteDirectoryName() {
FileDialog dialog = new FileDialog(new Frame(), "Enter file
name",FileDialog.SAVE);
dialog.show();
String fs = dialog.getDirectory();
System.out.println("Opening file: "+fs);
dialog.dispose();
return FilterFileNameBug(fs);
}
//
Some versions of windows will
//
create a .* suffix on a file name
//
The following code will strip it:
public
static String FilterFileNameBug(String fname) {
if (fname.endsWith(".*.*")) {
fname=fname.substring(0, fname.length() - 4);
}
return fname;
}
public static File getWriteFile() {
return new File(getWriteFileName());
}
public static File getDirFile() {
return new File(Ls.getDirName());
}
public static File getReadFile() {
return new File(getReadFileName());
}
public
static FileInputStream getFileInputStream() {
return getFileInputStream(getReadFileName());
}
public
static FileInputStream getFileInputStream(String name) {
FileInputStream fis = null;
try
{fis = new FileInputStream(name);}
catch (IOException e)
{System.out.println("futil:Could not open file");}
return fis;
}
public
static FileInputStream getFileInputStream(File file) {
FileInputStream fis = null;
try
{fis = new FileInputStream(file);}
catch (IOException e)
{System.out.println("futil:Could not open file");}
return fis;
}
public
static FileOutputStream getFileOutputStream() {
FileOutputStream fos = null;
try {fos =
new FileOutputStream(getWriteFileName());
}
catch (IOException e) {
System.out.println("futil:Could not create file");
}
return fos;
}
//
Open the file, return -1 if file cannot be opened
//
otherwise return the size in bytes
public
static int available(File file) {
FileInputStream fis = null;
int sizeInBytes = -1;
try {
fis = new FileInputStream(file);
sizeInBytes = fis.available();
fis.close();
}
catch (IOException e)
{System.out.println("Futil:Could not open file");}
return sizeInBytes;
}
public static void closeOutputStream(OutputStream os) {
try {os.close();} // end try
catch (IOException exe)
{System.out.println("futil: could not close output stream");}
}
public static void closeInputStream(InputStream is) {
try {is.close();} // end try
catch (IOException exe)
{System.out.println("futil: could not close input stream");}
}
public static void lsWordPrintMerge() {
String wild = "pict";
String[] files = Ls.getWildNames(wild);
System.out.println(files.length + " file(s):");
for (int i=0; i < files.length; i++)
System.out.println("\t" + files[i]);
}
static public void filterHtmls() {
String[] files = Ls.getWildNames(".html");
File input_dir = getDirFile();
System.out.println(files.length + " file(s) to process");
File output_dir = new File(input_dir.getParent(),"out");
if (output_dir.exists())
{System.out.println("Output dir exists:"+
output_dir);}
else {output_dir.mkdir();}
for (int i=0; i < files.length; i++) {
writeFilteredHrefFile(input_dir+files[i],output_dir+"/"+files[i]);
}
}
public
static void writeFilteredHrefFile(String inputName, String
outputName)
{
System.out.println("Filtering:\t" + inputName +"\t>\t"+outputName);
try {
FileInputStream is = new FileInputStream(inputName);
StreamTokenizer tokens = new StreamTokenizer(is);
FileOutputStream os = new FileOutputStream(outputName);
PrintStream output = new PrintStream(os);
int i;
int next = 0;
tokens.resetSyntax();
tokens.wordChars(0,255);
tokens.quoteChar('"');
while ((next = tokens.nextToken()) != tokens.TT_EOF) {
switch (next) {
case '"':
output.print('"');
for (i=0;i<tokens.sval.length();i++)
if (tokens.sval.charAt(i) == ' ')
output.print("%20");
else
output.print(tokens.sval.charAt(i));
output.print('"');
break;
case tokens.TT_WORD:
output.print(tokens.sval+" ");
break;
case tokens.TT_NUMBER:
output.print(tokens.nval+" ");
break;
case tokens.TT_EOL:
output.println();
break;
} // end switch
} // end while
is.close();
os.close();
} // end try
catch (Exception exe)
{System.out.println("writeFilteredHrefFile:er!");}
}
public static void main(String[] args) {
String name = getReadFileName( ) ;
System.out.println("HEllo world, I got:"+name);
try {
System.in.read(); // prevent console window from
going
away
} catch (java.io.IOException e) {}
}
public static void writeFilteredJavaFile( ) {
try {
FileInputStream is = getFileInputStream();
StreamTokenizer tokens = new StreamTokenizer(is);
PrintStream output = System.out;
int i;
int next = 0;
tokens.resetSyntax();
tokens.wordChars(0,255);
tokens.quoteChar(';');
while ((next = tokens.nextToken()) != tokens.TT_EOF) {
switch (next) {
case ';':
output.print("got a line:"+tokens.lineno());
break;
case tokens.TT_WORD:
output.print(tokens.sval+" ");
break;
case tokens.TT_NUMBER:
output.print(tokens.nval+" ");
break;
case tokens.TT_EOL:
output.println();
break;
} // end switch
} // end while
is.close();
} // end try
catch (Exception exe)
{System.out.println("writeFilteredHrefFile:er!");}
}
public static void list_filtered_href_file(String file) {
System.out.println("processing:\t" + file);
try {
FileInputStream input_file = new
FileInputStream(file);
StreamTokenizer tokens = new
StreamTokenizer(input_file);
int next = 0;
tokens.resetSyntax();
tokens.wordChars(0,255);
tokens.quoteChar('"');
while ((next = tokens.nextToken()) != tokens.TT_EOF)
{
switch (next) {
case '"':
System.out.print('"');
StringTokenizer st =
new
StringTokenizer(tokens.sval,"
");
while (st.hasMoreTokens()) {
System.out.print(st.nextToken());
if
(st.countTokens()
> 1)
{System.out.print("%20");}
}
System.out.print('"');
break;
case tokens.TT_WORD:
System.out.print(tokens.sval+" ");
break;
case tokens.TT_NUMBER:
System.out.print(tokens.nval+" ");
break;
case tokens.TT_EOL:
System.out.println();
break;
}
}
System.out.println();
input_file.close();
}
catch (Exception exe)
{System.out.println("list_filtered_href_file:er!");}
}
public
static void filterFileHrefs() {
FileInputStream fis = getFileInputStream();
StreamTokenizer tokens = new StreamTokenizer(fis);
int next = 0;
tokens.resetSyntax();
tokens.wordChars(0,255);
tokens.quoteChar('"');
try { while ((next = tokens.nextToken())
!= tokens.TT_EOF) {
switch (next) {
case '"':
System.out.print('"');
StringTokenizer st =
new StringTokenizer(tokens.sval," ");
while (st.hasMoreTokens()) {
System.out.print(st.nextToken());
if (st.countTokens() > 1)
{System.out.print("%20");}
}
System.out.print('"');
break;
case tokens.TT_WORD:
System.out.print(tokens.sval+" ");
break;
case tokens.TT_NUMBER:
System.out.print(tokens.nval+" ");
break;
case tokens.TT_EOL:
System.out.println();
break;
} // switch
}} // try while
catch (IOException e) {
System.out.println("Futil:ER! filterFileHrefs");
}
System.out.println();
closeInputStream(fis);
}
public static void processJava() {
FileInputStream fis = getFileInputStream();
String line;
DataInputStream dis = new DataInputStream(fis);
System.out.println("<HTML><BODY><PRE>");
try { while ((line = dis.readLine()) != null)
System.out.println(line);
}
catch (IOException e) {
System.out.println("Futil: ER! in processJava");
}
System.out.println("</PRE></BODY></HTML>");
closeInputStream(fis);
}
public
void lowerFileNames( File thePath ){
String[] fileNames = thePath.list();
String pathstr = thePath.getPath();
for( int i=0;
fileNames != null &&
i< fileNames.length; i++ ) {
String aFileName = fileNames[ i ];
String newFileName = aFileName.toLowerCase();
File theFile = new File( pathstr, aFileName );
if( theFile.isFile() ){
//rename theFile to lower case
System.out.print( i+":" + aFileName );
theFile.renameTo( new File( pathstr, newFileName ) );
System.out.println( "\t==>\t"+newFileName );
}else{
//case theFile is Dir, in the Dir, repeat same procedure
System.out.println( "Dir:"+aFileName );
lowerFileNames( new File( pathstr+aFileName ));
}
}
return;
}//lowerFileNames
public static void makeTocHtml() {
File dir = getDirFile();
String[] files = dir.list(new FileFilter());
System.out.println(files.length + " file(s):");
FileOutputStream fos = getFileOutputStream();
PrintStream ps = new PrintStream(fos);
ps.println("<HTML>");
ps.println("<BODY>");
ps.println("<ul>");
for (int i=0; i < files.length; i++)
ps.println("<LI><a href = \"" + files[i]+"\">"+
files[i]+"</a><P>");
ps.println("</ul>");
ps.println("</BODY>");
ps.println("</HTML>");
closeOutputStream(fos);
}
public static void readDataFile(String file,double data[]) {
System.out.println("processing:\t" + file);
FileInputStream inputFile =
getFileInputStream(file);
StreamTokenizer tokens = new StreamTokenizer(inputFile);
int next = 0;
int num = 0;
try {
while ((next = tokens.nextToken()) != tokens.TT_EOF) {
switch (next) {
case tokens.TT_WORD:
break;
case tokens.TT_NUMBER:
data[num] = (double) tokens.nval;
System.out.println(num+": "+ data[num]);
num = num + 1;
break;
case tokens.TT_EOL:
break;
}
}
}
catch (Exception exe)
{System.out.println("listFilteredHrefFile:er!");}
closeInputStream(inputFile);
}
}
How
do I build a custom streamtokenizer?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I build a custom streamtokenizer?
Date:
Wed, 11 Nov 1998 16:50:20 -0400
In
the last class, I covered
the
building of a custom stream tokenizer.
Sorry
to say, I forgot the reset for the
syntax.
What follows is an excerpt from
the
futils program that shows you how
to
reset the syntax on the stream tokenizer:
public
static void filterFileHrefs() {
FileInputStream fis = getFileInputStream();
StreamTokenizer tokens = new StreamTokenizer(fis);
int next = 0;
tokens.resetSyntax();
tokens.wordChars(0,255);
tokens.quoteChar('"');
try { while ((next = tokens.nextToken())
!= tokens.TT_EOF) {
switch (next) {
case '"':
System.out.print('"');
//Hey
class, check out the use of the
//
StringTokenizer...pretty neat, huh?
StringTokenizer st =
new StringTokenizer(tokens.sval," ");
//I
took the string from the stream tokenizer, then
//
processed it more with the string tokenizer....
//
The " " used in the constructor gives us the delimiter
//
for the string tokenizer....the tokens.sval gives
//
us the string to parse for this string tokenizer....
//
So, the stream tokenizer is set to stop at quote marks...
//
but the string tokenizer stops at spaces...according to
//
this usage. Got it? See the end of chapter 4 for
//
more info (pp 208-210 for people with a book)....DL
while (st.hasMoreTokens()) {
System.out.print(st.nextToken());
if (st.countTokens() > 1)
{System.out.print("%20");}
}
System.out.print('"');
break;
case tokens.TT_WORD:
System.out.print(tokens.sval+" ");
break;
case tokens.TT_NUMBER:
System.out.print(tokens.nval+" ");
break;
case tokens.TT_EOL:
System.out.println();
break;
} // switch
}} // try while
catch (IOException e) {
System.out.println("Futil:ER! filterFileHrefs");
}
System.out.println();
closeInputStream(fis);
}
How
should I save to a file?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How should I save to a file?
Date:
Sat, 21 Nov 1998 08:39:45 -0400
r,g,
and b are three arrays of short being written
into
a gzip file....
- DL
public
void saveAsShortgz(String fn) {
Timer t = new Timer();
t.start();
try {
FileOutputStream fos = new FileOutputStream(fn);
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gos);
oos.writeObject(r);
oos.writeObject(g);
oos.writeObject(b);
oos.close();
gos.finish();
} catch(Exception e) {
System.out.println("Save saveAsShortgz:"+e);
}
t.stop();
t.print(" saveAsShortgz in ");
}
private void readShortsGz(String fn){
Timer t = new Timer();
t.start();
GZIPInputStream in = null;
try {
in = new GZIPInputStream(
new FileInputStream(fn));
} catch(Exception e)
{e.printStackTrace();}
getShortImageGz(in);
t.print("End ReadShorts");
}
How
do I read and write gzipped objects with java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I read and write gzipped objects with java?
Date:
Sat, 21 Nov 1998 09:54:55 -0400
Here
is an example of how to treat objects
as
compressed file streams for reading and writing....
public
static void main(String args[]) {
System.out.println("Test");
SaveFrame f = new SaveFrame("save frame");
f.show();
float flt[][] =
{
{1.0f,3.0f,4.0f},
{1.0f,3.0f,4.0f},
{1.0f,3.0f,4.0f}
};
String fn = f.getSaveFileName("flt.gz file");
f.saveAsFloatgz(fn,flt);
f.readAsFloatgz(fn,flt);
for (int i=0; i < flt.length; i++)
for (int j=0; j < flt[0].length; j++){
System.out.println(flt[i][j]);
}
}
public
void saveAsFloatgz(float f[][]) {
saveAsFloatgz(
getSaveFileName("flt.gz file"), f);
}
public
static void saveAsFloatgz(String fn, float f[][]) {
try {
FileOutputStream fos = new FileOutputStream(fn);
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gos);
oos.writeObject(f);
oos.close();
gos.finish();
} catch(Exception e) {
System.out.println("Save saveAsFloatgz:"+e);
}
}
public
static void readAsFloatgz(String fn, float f[][]) {
try {
FileInputStream fis = new FileInputStream(fn);
GZIPInputStream gis = new GZIPInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(gis);
f = (float [][])ois.readObject();
ois.close();
} catch(Exception e) {
System.out.println("Save readAsFloatgz:"+e);
}
}
public
String getSaveFileName(String prompt) {
FileDialog fd = new
FileDialog(this, prompt, FileDialog.SAVE);
fd.setVisible(true);
fd.setVisible(false);
String fn=fd.getDirectory()+fd.getFile();
if (fd.getFile() == null) return null; //usr canceled
return fn;
}
how
do I display a directory?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
how do I display a directory?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
//
Vaguely useful program: Displays subtree of any directory showing how many
//
files and their total length. (Useful when trying to reclaim disk space)
import
java.io.*;
class
Tree
{
static
String indent=""; // Build tree-like indentation
long total=0; // Tot up storage used
int files=0; // Count files in directory
int dirs=0; // Count sub-directories
Tree(String
path,boolean first) // Are we first subtree?
{
indent+=first ? " " : "3 ";
int i;
for(i=path.length();i>0 && path.charAt(i-1)=='\\';i--); // Lose
trailing
\'s
File f=new File(path.substring(0,i));
String name[]=f.list(); // Get all the files in this directory
if(name!=null)
for(i=0;i<name.length;i++)
{
String temp=path+File.separator+name[i]; // Rebuild full path
f=new File(temp);
if(f.isDirectory()) // Does this name represent a
sub-directory/
{Tree t=new
Tree(temp,dirs==0);dirs++;total+=t.total;files+=t.files;}
else {files++;total+=f.length();} // If a file, then just add
in
its length
}
indent=indent.substring(0,indent.length()-2); // Unwind indentation
System.out.println(indent+(first ? "ÚÄ" :
"ÃÄ")+back(path)+"
"+files+","+total);
}
String
back(String path) // Return last name in a path
{
int i=path.lastIndexOf(File.separator);
return(path.substring(i+1));
}
public
static void main(String args[])
{
if(args.length==0)
{
String dir = System.getProperty( "user.dir" );
new Tree(dir,true); // Display current directory & subtree
}
else if(args.length==1)
new Tree(args[0],true);// Display specific directory
else
System.out.println("Requires directory name");
}
}
How
do I send e-mail in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I send e-mail in Java?
Date:
Thu, 12 Nov 1998 09:27:58 -0400
package
net;
import
java.applet.*;
import
java.awt.*;
import
java.net.*;
import
java.io.*;
import
java.util.Date;
import
gui.ClosableFrame;
public
class SendMail extends Applet
{
// The e-mail address all messages are to be sent to; specified in HTML
String webmasterEmail = null;
String serverHostName = null;
boolean standalone = false;
int smtpPort = 25;
Socket socket;
PrintStream ps;
DataInputStream dis;
InetAddress rina;
InetAddress lina;
Form form;
/**
* Initialize the applet.
*/
public void init()
{
setBackground(Color.white);
form = new Form(this);
add(form);
resize(600, 450);
if (serverHostName == null) serverHostName =
getCodeBase().getHost();
if (webmasterEmail == null) webmasterEmail =
getParameter("RECIPIENT");
}
/**
* Show status to the user.
*/
public void showStatus(String s)
{
System.out.println(s);
if (standalone) return;
super.showStatus(s);
}
/**
* Send an e-mail message.
*/
public void send()
throws IOException, Exception
{
// Open connection to SMTP server
socket = new Socket(serverHostName, smtpPort);
// Send the form contents as a message
try
{
rina = socket.getInetAddress();
lina = rina.getLocalHost();
ps = new PrintStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
// Send message
sendline("HELO " + lina.toString());
sendline("MAIL FROM:" + form.email());
sendline("RCPT TO:" + webmasterEmail);
sendline("DATA");
sendline(form.message());
sendline(".");
}
catch (Exception ex)
{
socket.close();
throw ex;
}
// Close connection
socket.close();
}
/**
* Send a line of data to the server, and retrieve the handshake
*/
void sendline(String data)
throws IOException
{
System.out.println("sendline out:" + data);
ps.println(data);
ps.flush();
String s = dis.readLine();
System.out.println("sendline in:" + s);
}
/**
* Main routine, for standalone program execution
*/
public static void main(String args[])
{
SendMail ap = new SendMail();
// The server host will be the place running POP
// webmaster e-mail will be recipient
ap.serverHostName = "yourmailserver";
ap.webmasterEmail = "your email address";
ap.standalone = true;
ClosableFrame fr = new ClosableFrame("SendMail");
ap.init();
fr.add("Center", ap);
fr.resize(600, 450);
fr.show();
ap.start();
}
}
/**
* A form for obtaining user input. Customize this for your application, just
* as you would customize an HTML form for a Web-based e-mail application.
*/
class
Form extends Panel
{
SendMail applet;
// The form's elements...
Label nameLabel;
TextField nameField;
Label emailLabel;
TextField emailField;
Label orgLabel;
TextField orgField;
Label msgBodyLabel;
TextArea msgBodyArea;
Button sendButton;
/**
* The constructor
*/
public Form(SendMail ap)
{
applet = ap;
setBackground(Color.white);
setLayout(new GridLayout(2, 1));
// Create a panel to put the text fields and button on
Panel p = new Panel();
p.setLayout(new GridLayout(8, 1));
// Instantiate all the elements, and add them to their
containers...
p.add(sendButton = new Button("Send"));
p.add(nameLabel = new Label("Your Name:"));
p.add(nameField = new TextField(60));
p.add(emailLabel = new Label("Your e-mail address:"));
p.add(emailField = new TextField(60));
p.add(orgLabel = new Label("Your orgainization:"));
p.add(orgField = new TextField(60));
p.add(msgBodyLabel = new Label("Your Message:"));
add(p);
add(msgBodyArea = new TextArea(3, 60));
// Set the size of the form
resize(550, 400);
}
/**
* Return the value in the e-mail address field in the form
*/
public String email()
{
return emailField.getText();
}
/**
* Return the contents of the body of the form, including any
"hidden"
fields.
*/
public String message()
{
String m = "";
m += nameLabel.getText();
m += nameField.getText();
m += "\n";
m += orgLabel.getText();
m += orgField.getText();
m += "\n";
m += "Web Origin:";
if (!applet.standalone) m += applet.getDocumentBase();
m += "\n";
m += "Date Sent:";
m += (new Date()).toString();
m += "\n";
m += msgBodyLabel.getText();
m += msgBodyArea.getText();
m += "\n";
return m;
}
/**
* Respond to the button click event: send the message.
*/
public boolean handleEvent(Event e)
{
if ((e.target == sendButton) && (e.id ==
Event.ACTION_EVENT))
{
// User clicked the Send button; send the message
try {applet.send();}
catch (Exception ex)
{
applet.showStatus("Error; message send
failed:\n
" + ex.toString());
return true;
}
applet.showStatus("Message sent");
return true;
}
// Not an event to handle; let the super class try
return super.handleEvent(e);
}
}
How
do I get an a name from an IP address in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I get an a name from an IP address in Java?
Date:
Thu, 12 Nov 1998 09:27:58 -0400
package
net;
import
java.net.InetAddress;
public
class DNS {
public static void getName(String name)
throws Exception
{
try {
InetAddress address =
InetAddress.getByName(name);
byte IP[] = address.getAddress();
for (int index = 0; index < IP.length;
index++) {
if (index > 0)
System.out.print(".");
System.out.print(
((int)IP[index])&
0xff);
}
System.out.println();
}
catch (Exception e)
{System.out.println(
"Feh, that was not a valid name!");}
} // getName
}
How
do I make a system console?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I make a system console?
Date:
Wed, 2 Dec 1998 05:52:31 -0400
//===========================================================================
//
SystemInput.java © 1996-1998 Metrowerks Inc. All
rights
reserved.
//===========================================================================
//
//
Created: 1/17/97
//
Author: Clinton Popetz
//
Revised for 1.1 by Scott Kovatch
//
//
These two classes just implement a simple System.in stream using a
//
TextField
//
//
- Cliff McCollum (cliffmcc@gulf.csc.uvic.ca) 8/25/97
//
//
Added the option to have all output automatically echoed to the output
//
window (like a real System.in would work).
//
//
- Cliff McCollum (cliffmcc@gulf.csc.uvic.ca) 11/26/97
//
Added support for Java 1.1.4 and CW Pro 2. This involved working around
//
a bug in the way BufferedReader and InputStream interact with
//
the Metrowerks Java console.
//
//
- Make SystemInput the only public class in this file. 3-12-98 -gdb
//
- Organize Cliff's ctors differently (main ctor has echo param, empty
//
ctor calls main ctor w/ echo true) 3-12-98 -gdb
//
- main defaults to echo on, since I like that 3-12-98 -gdb
//
- Move newLineChar into SystemInput, since its only used there. 3-12-98 -gdb
//
- add cmd line switch to set echo. If there is no switch, it defaults to
on
3-12-98 -gdb
package
com.mw;
import
java.awt.*;
import
java.io.*;
import
java.lang.*;
import
java.awt.event.*;
interface
SystemInConstants {
static final char marker = '\uFFFF';
}
public
class SystemInput extends Frame implements SystemInConstants,
KeyListener
{
static final char newLineChar = 0x000A;
static SystemInput sFrame; //no GC
SettableStringInputStream stream;
TextField field;
static boolean echoOutput;
// Here's the usage for the arg:
// -echo -> echo is on
// -noecho -> echo is off
// if there is no arg, it defaults to echo on.
public static void main(String [] argv)
{
if (sFrame == null)
{
if (argv.length > 0)
{
if (argv[0].equals("-noecho"))
new SystemInput(false);
else
new SystemInput();
}
else
new SystemInput(); // Let's default to
echo,
I like that. -gdb
}
else
sFrame.toFront();
}
public Insets getInsets() {
return new Insets (5, 5, 20, 5);
}
// - Cliff McCollum 8/25/97
// New constructor for receiving echo setting
public
SystemInput(boolean inEcho)
{
super("System.in");
sFrame = this; //no GC
// - Cliff McCollum 8/25/97
// Holds a flag indicating whether we should echo the output.
// On by default.
echoOutput = inEcho;
stream = new SettableStringInputStream(this);
System.setIn(stream);
// - Cliff McCollum 8/25/97
// If we really want this to work like the JDK, then we
should
make sure
// we can display at least 80 characters in the input window.
field = new TextField(80);
field.addKeyListener(this);
add("North", new Label("System input should be entered
here."));
add("Center",field);
pack();
show();
}
public
SystemInput()
{
this(true);
}
public void keyPressed(KeyEvent e) {
// If we get a CMD-D, set a marker character in the buffer.
if ((e.getKeyCode() == KeyEvent.VK_E && e.isMetaDown()) ||
e.getKeyCode()
== KeyEvent.VK_ENTER) {
String theText = field.getText();
// add the newline to the buffer if an enter or
return
was pressed
if (e.getKeyCode() != KeyEvent.VK_E) {
theText += newLineChar;
// - Cliff McCollum 11/27/97
// There is an important behaviour here. If
you
use the BufferedReader
// class, it will eventually call
InputStream
with a large (8192 bytes)
// buffer. InputStream will keep reading
until
this buffer is
// completely full, or it receives an EOF.
To
prevent this problem,
// we need to tack an EOF character onto
the
end of our buffer
// after every enter or return.
theText += marker;
} else {
// add the marker character to the buffer
theText += marker;
}
stream.MoreData(theText);
field.setText("");
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void toFront()
{
super.toFront();
field.requestFocus();
}
}
class
SettableStringInputStream extends InputStream implements
SystemInConstants
{
protected String buffer = "";
protected int pos = 0;
protected SystemInput mFrame;
public SettableStringInputStream (SystemInput inNewFrame)
{
mFrame = inNewFrame;
}
public synchronized void MoreData(String data)
{
// - Cliff McCollum 8/25/97
// Here's the echo checking
//
// - Cliff McCollum 11/27/97
// Unfortunately, due to the complications with the
BufferedReader
(see above)
// we need to check for the marker character on the end of
this
string. If
// it's present, we need to make sure we don't print it.
if (SystemInput.echoOutput) {
String temp = new String(data);
int theLen = temp.length();
if (temp.charAt(theLen-1) == marker) {
temp = temp.substring(0, theLen-2);
}
System.out.print(temp);
// - Cliff McCollum 11/27/97
// We need to print a newline to mimic the
behaviour
of Sun's JDK
System.out.print("\n");
}
buffer += data;
notify();
}
public synchronized int read() throws IOException
{
try {
if (buffer.length() <= pos)
{
mFrame.toFront();
wait();
}
char c = buffer.charAt(pos++);
if (c == marker || pos == buffer.length()) //used up this
string,
reset it
{
pos = 0;
buffer = "";
}
// If we find the marker char in the buffer, return
-1
for EOF.
if (c == marker)
return -1;
else
return c;
}
catch (InterruptedException e) {
return -1;
}
}
public int available() {
return buffer.length() - pos;
}
}
How
do I parse a string: "className.method"
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I parse a string: "className.method"
Date:
Mon, 7 Dec 1998 19:35:24 -0400
One
way to do this is to use the string methods...another
way
is to make an instance of a stream tokenizer.
String
s = "className.method";
int
i = s.indexOf('.');
OK?
- DL
>Dear
Prof.
>
>When
the user types:
>className.method
>
>how
can I separate className and method name?
>
>Thanks
>Jiyoung
An
how
do I convert a string to an int?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
how do I convert a string to an int?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
class
Conv
{
static
public void main(String args[])
{
// String to integer
System.out.println(Integer.valueOf("123").intValue());
// Or less confusingly:
String s="123";
Integer i=Integer.valueOf(s);
int j=i.intValue();
System.out.println(j);
// Or better: (parseInt returns int, while valueOf returns Integer)
j=Integer.parseInt("123");
System.out.println(j);
// Convert int to String
i=new Integer(j);
s=i.toString();
System.out.println(s);
// which is the same as
System.out.println(new Integer(j).toString());
}
}
How
do I get the methods from a class?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I get the methods from a class?
Date:
Thu, 3 Dec 1998 09:44:37 -0400
To get the methods from a class, use:
Class c = (Class)v.elementAt(i);
System.out.println(c);
printMethods(c.getMethods());
- DL
>Dear
Prof,
>I
have used getMethod to return an array of methods on the class. I
>wanted
to know whether the methods related are of the specific class
>that
i pass as parameter for getMethods or all the classes that are
>imported
in the program.
>Apurva
More
>
>______________________________________________________
>Get
Your Private, Free Email at
http://www.hotmail.com
How
do I write help?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I write help?
Date:
Thu, 3 Dec 1998 11:40:30 -0400
Hi
All,
If
a user types:
help
TopFrame
The
getMethods() will return all the methods available to
an
instance of the TopFrame class. It is OK to print
all
the methods, you do not have to differentiate from
super-classes
and sub-classes.
I
hope that this helps to simplify the homework a little.
Thanks!
- DL
>hi,
professor,
>Because
getMethods() Returns an array containing Method objects
>reflecting
all the public member methods of the class or interface
>represented
by this Class object, including those declared by the class
>or
interface and and those inherited from
>superclasses
and superinterfaces. So if user types 'help className', how
>can
we just return all the methods just in the class?
>
>best
regards
>zhenheng
wang
How
to I add meta tags?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How to I add meta tags?
Date:
Mon, 9 Nov 1998 10:12:44 -0400
When
formulating a web page, it is
very
important to have meta tags in the HTML.
This
will help search engines index your
web
page and thus help people find your
web
page.
What
follows are a list of some meta tag examples
and
further hints:
------- Begin cut ------
<title>Distance Learning Homepage</title>
------- End cut -----
Keyword
META Tag:
------- Begin cut ------
<meta name="keywords" content="Digital Signal Processing Java Image
Processing
Computer Networks Digitial Design ">
------- End cut -----
Description
META Tag:
------- Begin cut ------
<meta name="description" content="Java, Networks, and Java DSP Home
Page">
------- End cut -----
All
these tags belong between your <head></head> tags within your HTML
document.
NOTE:
If you use an HTML editor (i.e. MS FrontPage, AOLPress, etc.) you may
need
to consult the help files to determine how to edit the raw HTML code.
If
you liked the tools at SiteOwner.com you may be interested in the other
services
we offer:
------------------------------------
Submit
It!: Announce you site to the world!
-
http://www.submit-it.com
------------------------------------
ClickTrade:
Point the web at your site!
-
http://www.clicktrade.com
------------------------------------
Listbot:
Get a FREE mailing list for your Web site!
-
http://www.listbot.com
------------------------------------
PositionAgent:
Monitor your rankings in all the major search engines!
-
http://www.positionagent.com
------------------------------------
SiteOwner.com:
The ultimate bookmark for web site owners!
-
http://www.siteowner.com
how
do I use a jar file?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
how do I use a jar file?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
//
To use this from a jar file:
//
javac Jar to produce the normal Jar.class file.
//
jar cvf Jar.jar Jar.class to create a jar file with just this class
//
jar cvf0 Jar.jar Jar.class does the same thing but with no compression
//
<applet code=Jar.class archive=Jar.jar width=400 height=350></applet>
//
will cause it to be executed out of Jar.jar
import
java.awt.*;
public
class jar extends java.applet.Applet
{
Button b=new Button("Jar applet");
public
void init()
{
add(b);
}
}
how
do I serialize an object?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
how do I serialize an object?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
Topics:
Overview
Writing Objects to a Stream
Reading Objects from a Stream
Protecting Sensitive Information
Fingerprints of Classes
Secure Hash Stream
Overview
The
capability to store and retrieve Java objects is essential
to
building all but the most transient applications. The key
to
storing and retrieving objects is representing the state of
objects
in a serialized form sufficient to reconstruct the
object(s).
For Java objects, the serialized form must be able
to
identify and verify the Java classes from which the fields
were
saved and to restore those fields to instances of the
same
classes. The serialized form does not need to include
the
complete class definition but requires that the class is
available
when needed.
Objects
to be stored and retrieved frequently refer to other
objects.
Those other objects must be stored and retrieved at
the
same time to maintain the relationships between the
objects.
When an object is stored all of the objects that are
reachable
from that object are stored as well.
The
goals for serializing Java objects are to:
Have a simple yet extensible mechanism.
Maintain the Java object type and safety properties in
the serialized form.
Be extensible to support marshaling and unmarshaling
as needed for remote objects.
Be extensible to support persistence of Java objects.
Require per class implementation only for
customization.
Writing
Objects to a Stream
Writing
objects and primitives to a stream is a straight
forward
process. For example:
//
Serialize today's date to a file.
FileOutputStream f = new FileOutputStream("tmp");
ObjectOutput s = new ObjectOutputStream(f);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
First
an OutputStream, in this case a
FileOutputStream,
is needed to receive the bytes.
Then
an ObjectOutputStream is created that writes to
the
OutputStream. Next, the string "Today" and a Date
object
are written to the stream. More generally, objects
are
written with the writeObject method and primitives
are
written to the stream with the methods of
DataOutputStream.
The
writeObject method serializes the specified object
and
traverses its references to other objects in the object
graph
recursively to create a complete serialized
representation
of the graph. Within a stream, the first
reference
to any object results in the object being serialized
and
the assignment of a handle to that object. Subsequent
references
to that object are encoded as the handle. Using
object
handles preserves sharing and circular references
that
occur naturally in object graphs. Subsequent references
to
an object use only the handle allowing a very compact
representation.
The
serialized encoding of an object consists of the object's
class
followed by the fields of each class starting with the
highest
superclass and ending with the actual class.
For
an object to handle its own serialization it must
implement
the writeObject method. To maintain the
integrity
of the class, this method is private to the class and
can
only be called by the serialization at runtime. This
method
is invoked when the fields of its class are to be
written;
it should write the information needed to
reinitialize
the object when it is deserialized.
The
default mechanism writes each non-static and
non-transient
field to the stream. Each field is written
appropriately
depending on its type. The fields are put in a
canonical
order so as to be insensitive to the order of
declaration.
Objects
of class Class are serialized as the name of the
class
and the fingerprint or hash of the interfaces, methods,
and
fields of the class. The name allows the class to be
identified
during deserialization and the hash of the class
allows
it to be verified against the class of the serialized
object.
All other normal Java classes are serialized by
writing
the encoding of its Class followed by its fields.
ObjectOutput
streams can be extended to customize the
information
in the stream about classes or to replace
objects
to be serialized. Refer to the annotateClass and
replaceObject
method descriptions for details.
Reading
Objects from a
Stream
Reading
an object from a stream is equally straight
forward:
//
Deserialize a string and date from a file.
FileInputStream in = new FileInputStream("tmp");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
First
an InputStream, in this case a
FileInputStream,
is needed as the source stream. Then
an
ObjectInputStream is created that reads from the
InputStream.
Next, the string "Today" and a Date
object
are read from the stream. More generally, objects
are
read with the readObject method and primitives are
read
from the stream with the methods of
DataInputStream.
The
readObject method deserializes the specified object
and
traverses its references to other objects recursively to
create
the complete graph of objects serialized. Objects
read
from the stream are type checked as they are assigned.
Reading
an object consists of the decoding of the object's
class
and the fields of each class starting with the highest
superclass
and ending with the actual class.
For
an object to handle its own serialization it must
implement
the readObject method. To maintain the
integrity
of the class, this method is private to the class and
can
only be called by the serialization at runtime. This
method
is invoked when the fields of its class are to be
read;
it should read the information written by
writeObject
and make appropriate assignments to the
object's
fields. If the state of the object cannot be
completely
restored at the time the object is being read, a
validation
callback can be requested by calling the
registerValidation
method.
The
default mechanism reads each non-static and
non-transient
field from the stream. Each field is read
appropriately
depending on its type. The fields are read in
the
same canonical order as when written so as to be
insensitive
to the order of declaration.
Objects
of class Class are deserialized as the name of the
class
and fingerprint. A fingerprint is a hash of the
interfaces,
methods, and fields of the class. The
resolveClass
method is called to find the class by name
and
return its Class object. The hash is computed for the
returned
class and compared with the hash of the class
serialized.
Deserialization proceeds only if the class
matches.
This ensures that the structure of the stream
matches
the structure of the class. All other normal Java
classes
are deserialized by reading the encoding of its Class
followed
by its fields.
ObjectInput
streams can be extended to utilize customized
information
in the stream about classes or to replace
objects
that have been deserialized. Refer to the
resolveClass
and resolveObject method
descriptions
for details.
Protecting
Sensitive
Information
Warning: The current implementation does not
protect the private fields of objects, and object
serialization, therefore, can be used to reveal
private information that must be kept secret. At
JDK 1.1, the implementation will require
programmers to explicitly declare which classes
can be serialized.
When
developing a class that provides controlled access to
resources,
care must be taken to protect sensitive
information
and functions. During deserialization (by
default)
the private state of the object is restored. For
example,
a file descriptor contains a handle that provides
access
to an operating system resource. Being able to forge
a
file descriptor would allow some forms of illegal access,
since
restoring state is done from a stream. Therefore, the
serializing
runtime must take the conservative approach
and
not trust the stream to contain only valid
representations
of objects. To avoid compromising a class,
the
sensitive state of an object must not be restored from
the
stream or it must be reverified by the class. Several
techniques
are available to protect sensitive data in classes.
The
easiest technique is to mark fields that contain
sensitive
data as "private transient". Transient and static
fields
are not serialized or deserialized. Simply marking
the
field will prevent the state from appearing in the stream
and
from being restored during deserialization. Since
writing
and reading (of private fields) cannot be superceded
outside
of the class, the class's transient fields are safe.
Particularly
sensitive classes should not be serialized at all.
To
accomplish this, writeObject and readObject
methods
should be implemented to throw the
NoAccessException.
Throwing an exception will abort
the
entire serialization or deserialization process before any
state
from the class can be serialized or deserialized.
Some
classes may find it beneficial to allow writing and
reading
but specifically handle and revalidate the state as it
is
deserialized. The class should implement
writeObject
and readObject methods to save and
restore
only the appropriate state. If access should be
denied,
throwing a NoAccessException will prevent
further
access.
Fingerprints
of Classes
Within
an object stream classes are represented by name
and
fingerprint. This fingerprint is used to verify that the
class
used to deserialize the object is the same as the class
of
the object serialized. The shallow signature or
fingerprint
of a class is computed by hashing the class
name
and access flags, the interfaces supported by the
class,
the field names, access flags and signatures, and the
method
names, access flags and signatures. Each set of
interfaces,
fields, and methods are put in a canonical order
prior
to hashing so that the order of declaration does not
affect
the hash. The shallow fingerprints of the class and all
superclasses
are rehashed to define the fingerprint of the
class
that is used in the stream.
The
FingerPrintClass implementation also provides a
total
fingerprint that includes the fingerprints of each class
referred
to by the class as a parameter or return value.
The
values and strings included in the hash are those of the
Java
Virtual Machine Specification that define classes,
methods,
and fields.
Secure
Hash Stream
The
SHAOutputStream provides an implementation of the
National
Institute of Standards and Technology (NIST)
Secure
Hash Algorithm (SHA). Its output is a 160-bit (20
byte)
secure hash of the bytes written.
//
This shows the use of the Java Serializable interface to provide the
function
//
of a file of records of different types.
import
java.io.*;
class
RecordIO
{
static
public void main(String args[]) throws Exception
{
ObjectOutputStream out=
new ObjectOutputStream(new FileOutputStream("temp.bin"));
ObjectInputStream in=
new ObjectInputStream(new FileInputStream("temp.bin"));
Employe joe=new Employe("Joe Smith",25,30.5);
Employee sarah=new Employee("Sarah Jones",31,38.3,"Morgan");
Employe bill=new Employe("Bill Brown",45,40.5);
Object o;
out.writeObject(joe);
out.writeObject(sarah);
out.writeObject(bill);
for(int i=0;i<3;i++)
{
o=in.readObject(); // We don't know what type it is
System.out.print(((Employe)o).name+", "+((Employe)o).age);
if(o instanceof Employee)
System.out.print(", nee "+((Employee)o).maidenname);
System.out.println();
}
}
}
class
Employe implements Serializable
{
public
String name;
public
int age;
double salary;
public
Employe(String n,int a,double s)
{
name=n;
age=a;
salary=s;
}
}
class
Employee extends Employe // This is a female employe
{
public
String maidenname;
public
Employee(String n,int a,double s, String mn)
{
super(n,a,s);
maidenname=mn;
}
}
How
do I unsubscribe?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I unsubscribe?
Date:
Fri, 5 Feb 1999 15:51:37 -0500
If
you ever want to remove yourself from this mailing list,
you
can send mail to <majordomo@vinny.bridgeport.edu> with the following
command
in the body of your email message:
unsubscribe cs410x-list
How
do I nest layouts in panels?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I nest layouts in panels?
Date:
Thu, 11 Feb 1999 13:38:33 -0500
The
following example shows
how
to nest layouts in panels. Note that
each
panel has its own layout manager.
Also
note that the pack method is only available
in
the fram (not the panel). Pack is required
because
it resizes the window to its preferred
size.
Frame extends window, but panel does not.
Further
only window has the pack method.
Finally,
the pack method called addNotify,
which
causes all the components in the container
hierarchy
to be created.
import
java.awt.*;
public
class PapPanel extends
Panel {
CpuPanel
cpuPanels[];
PapPanel(
int numberOfCPUs) {
cpuPanels =
new CpuPanel[numberOfCPUs];
setLayout(
new GridLayout(4,5));
for (int i=0;
i < numberOfCPUs; i++) {
cpuPanels[i]=new CpuPanel(i);
add(cpuPanels[i]);
}
}
}
public
class Display extends
Frame {
public CpuPanel[]
addCpus(int N) {
setLayout(new
GridLayout(2,1));
PapPanel pap =
new PapPanel(N);
add (pap);
add (new BCP());
pack();
return pap.cpuPanels;
}
public static void main(String args[]) {
System.out.println( "Hello World!" );
Display d = new Display();
CpuPanel cpus[]=d.addCpus(20);
d.setVisible(true);
for (int i =0; i<cpus.length;i++) {
cpus[i].setSpeed(i*2+1);
}
d.repaint();
try {
System.in.read(); // prevent console window from
going
away
} catch (java.io.IOException e) {}
}
}
public
class BCP
extends Panel {
BCP() {
setLayout(
new GridLayout(1,2));
add(new Button("update"));
add(new
Button("Terminate"));
}
}
public
class CpuPanel
extends Panel {
Label speedLabel =
new Label(" 0");
CpuPanel(int cpuNumber) {
setLayout(new
GridLayout(2,1));
add(speedLabel);
add(new Label
("CPU "+cpuNumber));
}
public void setSpeed(float speed) {
speedLabel
= new Label(speed+"");
}
}
How
do I check my mail with Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I check my mail with Java?
Date:
Thu, 12 Nov 1998 09:27:58 -0400
package
net;
import
java.applet.*;
import
java.awt.*;
import
java.net.*;
import
java.applet.*;
import
java.io.*;
import
java.util.Date;
import
gui.ClosableFrame;
/**
* The applet.
*/
public
class CheckMail extends Applet
{
String serverHostName = null;
boolean standalone = false;
int popPort = 110;
Socket socket;
PrintStream ps;
DataInputStream dis;
InetAddress rina;
InetAddress lina;
CheckMailForm form;
/**
* Initialize the applet.
*/
public void init()
{
form = new CheckMailForm(this);
add(form);
form.resize(300, 300);
setBackground(Color.blue);
if (serverHostName == null) serverHostName =
getCodeBase().getHost();
}
/**
* Show status text to the user.
*/
public void showStatus(String s)
{
System.out.println(s);
if (standalone) return;
super.showStatus(s);
}
/**
* Perform check for e-mail.
*/
public void checkForMail()
throws IOException, NumberFormatException, Exception
{
showStatus("Checking for mail on " + serverHostName);
// Open connection
socket = new Socket(serverHostName, popPort);
String rs;
try
{
rina = socket.getInetAddress();
lina = rina.getLocalHost();
ps = new PrintStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
// Check for messages
sendline("USER " + form.getId());
rs = sendline("PASS " + form.getPswd());
if (rs.charAt(0) != '+') throw new
Exception("Incorrect
password");
rs = sendline("STAT");
}
catch (Exception ex)
{
socket.close();
throw ex;
}
// Close connection
socket.close();
// Parse result
int r = 0;
r = Integer.parseInt(rs.substring(4, rs.indexOf(" messages")));
// Update result field
form.resultField.setText(Integer.toString(r));
}
/**
* Send a line of data to the server, and return the handshake.
*/
String sendline(String data)
throws IOException
{
System.out.println("sendline out:" + data);
ps.println(data);
ps.flush();
String s = dis.readLine();
System.out.println("sendline in:" + s);
return s;
}
/**
* Main routine, for running as a standalone application.
*/
public static void main(String args[])
{
CheckMail ap = new CheckMail();
ap.serverHostName = "mail.snet.net";
ap.standalone = true;
ClosableFrame fr = new ClosableFrame("CheckMail");
ap.init();
fr.add("Center", ap);
fr.resize(300, 300);
fr.show();
ap.start();
}
}
/**
* Form for obtaining e-mail user id and password from the user.
*/
class
CheckMailForm extends Panel
{
CheckMail applet;
// The form's elements...
Label idLabel;
TextField idField;
Label pswdLabel;
TextField pswdField;
Button button;
Label resultLabel;
TextField resultField;
/**
* The constructor.
*/
public CheckMailForm(CheckMail ap)
{
applet = ap;
setBackground(Color.blue);
setLayout(new GridLayout(7, 1));
// Instantiate all the elements, and add them to the form...
add(button = new Button("Check For Mail"));
add(idLabel = new Label("Id:"));
add(idField = new TextField(20));
add(pswdLabel = new Label("Password:"));
add(pswdField = new TextField(20));
pswdField.setEchoCharacter('*');
add(resultLabel = new Label("Messages Waiting:"));
add(resultField = new TextField(6));
resultField.setEditable(false);
// Set the size of the form
resize(250, 250);
}
/**
* Return the value of the ID field in the form.
*/
public String getId()
{
return idField.getText();
}
/**
* Return the value of the password field in the form.
*/
public String getPswd()
{
return pswdField.getText();
}
/**
* Respond to the button click event: check for messages.
*/
public boolean handleEvent(Event e)
{
if ((e.target == button) && (e.id == Event.ACTION_EVENT))
{
try {applet.checkForMail();}
catch (Exception ex)
{
applet.showStatus("Error; unable to check
for
messages:\n "
+ ex.toString());
return true;
}
applet.showStatus("Completed.");
return true;
}
return super.handleEvent(e);
}
}
How
do I get an address from a name in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I get an address from a name in Java?
Date:
Thu, 12 Nov 1998 09:27:58 -0400
package
net;
import
java.applet.Applet;
import
java.awt.*;
import
java.net.*;
import
java.io.*;
public
class SearchDNS extends Applet {
//--------------------------------------------------------------
TextField searchField;
//--------------------------------------------------------------
public void init() {
Label title = new Label(
"Enter a name to get an IP address");
title.setFont(
new Font("Helvetica", Font.BOLD, 18));
title.setBackground(Color.red);
title.setForeground(Color.yellow);
add(title);
add(new Button("Use DNS"));
searchField = new TextField(20);
add(searchField);
}
//--------------------------------------------------------------
// Events from *either* Button or TextField should trigger this.
public boolean action(Event event, Object object)
{
String searchString = searchField.getText();
if (searchString.equals(""))
searchString = "cse.bridgeport.edu";
try { DNS.getName(searchString);}
catch (Exception e) {};
return(true);
}
}
How
to I read and Write a gzipped file of floats?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How to I read and Write a gzipped file of floats?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
Hi
All,
Here
is how to read and write a gzipped file of
floats.
To test this class, please place it in the gui
package
of Kahindu and run
gui.MatFloat
(which has its own main).
Please
take some time to look this over...
Thanks!
- DL
package
gui;
import
java.io.*;
import
java.awt.*;
import
java.util.zip.*;
public
class MatFloat extends
Mat {
float f[][];
MatFloat
(float flt[][]) {
f = flt;
}
public
String getSaveFileName(String prompt) {
FileDialog fd = new
FileDialog(
new Frame(),
prompt,
FileDialog.SAVE);
fd.setVisible(true);
fd.setVisible(false);
String fn=fd.getDirectory()+fd.getFile();
if (fd.getFile() == null) return null; //usr canceled
return fn;
}
public
static void main(String args[]) {
System.out.println("Test");
float flt[][] =
{
{1.0f,3.0f,4.0f},
{1.0f,3.0f,4.0f},
{1.0f,3.0f,4.0f}
};
MatFloat mf = new MatFloat(flt);
print(flt);
String fn = mf.getSaveFileName("flt.gz file");
mf.saveAsgz(fn);
mf.readAsgz(fn);
print(mf.f);
}
public
void saveAsgz() {
saveAsgz(
getSaveFileName("flt.gz file"));
}
public
void saveAsgz(String fn) {
try {
FileOutputStream fos = new FileOutputStream(fn);
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gos);
oos.writeInt(f.length);
oos.writeInt(f[0].length);
for (int x=0; x < f.length; x++)
for (int y=0; y < f.length; y++)
oos.writeFloat(f[x][y]);
oos.close();
gos.finish();
} catch(Exception e) {
System.out.println("Save saveAsFloatgz:"+e);
}
}
private
void readAsgz(String fn) {
try {
FileInputStream fis = new FileInputStream(fn);
GZIPInputStream gis = new GZIPInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(gis);
int w = ois.readInt();
int h = ois.readInt();
f = new float[w][h];
for (int x=0; x < w; x++)
for (int y=0; y < h; y++)
f[x][y] = ois.readFloat();
ois.close();
} catch(Exception e) {
System.out.println("readAsgz:"+e);
}
}
}
How
do I do a client server with sockets in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I do a client server with sockets in Java?
Date:
Sun, 22 Nov 1998 09:47:29 -0400
import
java.io.*;
import
java.net.*;
//
To run issue 'start java Server' which will set the server listening on
port
1234
//
Then issue 'java Client' from the original session
class
Server
{
public
static void main(String[] args)
{
System.out.println("Starting Server listening on 1234 ...");
try
{
ServerSocket ss= new ServerSocket(1234);
Socket s = ss.accept();
PrintStream out = new PrintStream(s.getOutputStream());
out.println("Server Connected");
s.close();
}
catch (Exception e) { System.out.println(e); }
}
}
class
Client
{
public
static void main(String[] args)
{
System.out.println("Client Looking...");
try
{
Socket s = new Socket(InetAddress.getLocalHost(),1234);
DataInputStream in = new DataInputStream(s.getInputStream());
System.out.println(in.readLine());
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("Done.");
}
}
How
do I set up for browsing?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I set up for browsing?
Date:
Tue, 24 Nov 1998 09:12:49 -0400
There
are several reasons for this.
1.
Location: Place the html and jar files in the .public_html
directory.
check:
http://www.bridgeport.edu/~yourUid/kahindu.html
http://www.bridgeport.edu/~lyon/kahindu.html
2.
Make sure the files are read accessable.
3.
Make an applet from the main...
>I
can browse the kahindu applet using netscape in local computer. But when
>I
put it in my directory, I can't browse it from internet.
>Why?
>
>
>xwan
How
do I make a Jar file from many directories?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I make a Jar file from many directories?
Date:
Tue, 24 Nov 1998 09:12:49 -0400
The
frame hierarchy of Kahindu is such that
a
single invocation of
jar
cvf classes.jar Main.class fft/*.class gui/*.class
htmlconverter/*.class
idx
/*.class
vs/*.class
should
make a classes.jar file for you...
- DL
>Sir,
I can't understand the frame hierachy of your kahindu program fully,
>so
I
>have
trouble in the homework. I can't init the applet correctly.
>could
you give me some kind of suggestions?
>Thank
you !
>
>xwan
How
do I build a command line Interpreter?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I build a command line Interpreter?
Date:
Wed, 25 Nov 1998 08:47:28 -0400
import
java.io.*;
import
java.util.*;
class
Foo {
public void run() {
System.out.println(
"Foo reporting for duty");
}
}
public
class TrivialApplication {
static String cn = "Foo";
public static void main(
String args[]) {
String ds =
"1.00001a";
try {
String
line;
DataInputStream
dis
= new DataInputStream(System.in);
while ((line=dis.readLine())
!= null) {
//System.out.println(line);
StringTokenizer st
= new StringTokenizer
(line);
int tokNum = 0;
while (st.hasMoreTokens() ) {
String
toks = st.nextToken();
//System.out.println(
// toks);
tokNum++;
if (tokNum == 1) {
try {
Object o =
Class.forName(toks).newInstance();
}
catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}
}
}
catch(Exception e) {
System.out.println(e);
}
String line;
try {
Foo a =
(Foo)Class.forName(cn).newInstance();
a.run();
}
catch (Exception e) {
System.out.println(
e);
}
System.out.println( "Hello World!" );
try {
System.in.read(); // prevent console window from
going
away
} catch (java.io.IOException e) {}
}
}
How
do I tell the type of an object
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I tell the type of an object
Date:
Mon, 30 Nov 1998 09:55:32 -0400
When
a reference is returned you may cast
it
to an instance of the Class type:
Object
o = v.elementAt(2);
Class
c = o.getClass();
String
typeString =
c.getName();
TypeString
contains a string description of the class
name.
- DL
>
Hi! Professor: Is there anyway to know the exact data type of
>the
objects stored in a vector? Such as, whether the element is of type
>String,
Double or something else?
>
>
Ming
How
do I hand in Late homework?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I hand in Late homework?
Date:
Thu, 1 Oct 1998 05:58:29 -0500
You
can fax it;
You
can e-mail it.
If
you slip it under a door, you must get a faculty or
staff
member to sign and date it.
A
time-stamp is required to document when a homework
is
handed in.
Regards,
- DL
>Date:
Wed, 30 Sep 1998 15:58:00 -0400
>From:
Rajendra Maharjan <rajendra@bridgeport.edu>
>X-Accept-Language:
en
>MIME-Version:
1.0
>To:
lyon@snet.net
>Subject:
submit homework # 3
>
>Hi
professor,
>
I am looking for you from morning to submit homework # 3 of CS 410.
>Since
you are not in the office, I slide the paper under your office
>door.
>thank
you
>
>Rajendra
Maharjan
>
>--
>Rajendra
maharjan
>80
University Ave, # 248
>Bridgeport,
CT 06604
>phone
# 203) 576-2133
>e-mail:
rajendra@bridgeport.edu
>URL:
http://www.bridgeport.edu/~rajendra
>
How
do I set the pict file type?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I set the pict file type?
Date:
Sat, 3 Oct 1998 10:05:33 -0500
Hi
Al,
The
below code is interesting,
but
I think that it is not going to work
at
all on windows....
- DL
>Dr
Lyon,
>I
modified FrameGrab's toFile(fn) method with the MRJ Toolkit API so
>that
it makes a simpletext pict. Now you wont have to drag the file onto
>your
cute little "make Simpletext" program.
>I
dunno what they would do in windoze.
>code
follows
>cheers
>allan
>
>
>
>//
Copyright 1998, Prof. D. Lyon
>//
>import
java.awt.*;
>import
quicktime.qd.*;
>import
quicktime.*;
>import
quicktime.std.StdQTConstants;
>import
quicktime.std.sg.*;
>import
quicktime.app.image.*;
>import
com.apple.mrj.*;
>import
java.io.*;
>public
class FrameGrab
>
implements
>
StdQTConstants {
>
>
public static void main (String args[]) {
>
FrameGrab fg = new FrameGrab();
>
fg.snapShot();
>
System.out.println("click");
>
}
>
>
private SequenceGrabber sg;
>
>
public static Image pictToImage(Pict inPict) {
>
ImageData id = null;
>
try {
>
id.fromPict(inPict);
>
} catch (Exception e) {
>
System.out.println(e);
>
};
>
QDRect r = id.getDisplayBounds();
>
Image i = null;
>
try {
>
i =
>
>Toolkit.getDefaultToolkit().createImage(new
>
QTImageProducer(
>
id, new
>
Dimension(
>
r.getWidth(),
>r.getHeight())));
>
>
}
>
catch (Exception e) {
>
System.out.println(e);
>
}
>
return i;
>
}
>
>
public void toFile() {
>
FileDialog fd = new FileDialog(
>
new Frame(),
>
"Gimme a pict name",
>
FileDialog.SAVE);
>
fd.show();
>
>
String fn= fd.getDirectory()+fd.getFile();
>
System.out.println(fn);
>
toFile(fn);
>
}
>
public void toFile(String fn) {
>
MRJOSType newType = new MRJOSType("PICT");
>
MRJOSType newCreator = new MRJOSType("ttxt");
>
MRJFileUtils.setDefaultFileType(newType);
>
MRJFileUtils.setDefaultFileCreator(newCreator);
>
File file =
>
new File(fn);
>
Pict p = getPict();
>
try {
>
p.writeToFile(file);
>
}
>
catch (Exception e) {
>
System.out.println(e);
>
};
>
}
>
public Image getImage() {
>
return pictToImage(getPict());
>
}
>
public Pict getPict() {
>
try {
>
sg = new SequenceGrabber();
>
}
>
catch (Exception e) {
>
System.out.println(e);
>
};
>
int offScreenDepth=8;
>
int grabPictFlags =
>
seqGrabToMemory |
>
seqGrabPreview |
>
seqGrabRecord |
>
seqGrabPlayDuringRecord ;
>
QDRect bounds=new QDRect(256,256);
>
Pict p = null;
>
try {
>
p = Pict.fromSequenceGrabber(
>
sg,
>
bounds,
>
offScreenDepth,
>
grabPictFlags);
>
}
>
catch (Exception e) {};
>
>
return p;
>
}
>
private void snapShot() {
>
try{
>
QTSession.open();
>
toFile();
>
} catch (Exception ee) {
>
ee.printStackTrace();
>
QTSession.close();
>
}
>
}
>
>}
How
do I use Gridbag Layout?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I use Gridbag Layout?
Date:
Mon, 5 Oct 1998 06:09:16 -0500
The
GridBag Layout has one constructor GridBagLayout(). The real trick to
GridBag
Layout control is the GridBagConstraints class. The actual
GridBagLayout
is in init().
import
java.applet.*;
import
java.awt.*;
public
class Car extends Applet implements Runnable
{
// All the Stuff needed for this Example
Thread m_Car = null;
// Line
private Canvas can = new Canvas();
// plan control
private boolean plan = true;
// components
private Label title1 = new Label("Personal Information",Label.CENTER);
private double f0 = 100.0;
// last
private Label l1 = new Label("Last Name",Label.CENTER);
private TextField t1 = new TextField("",20);
// first
private Label l2 = new Label("First Name",Label.CENTER);
private TextField t2 = new TextField("",20);
// age
private Label lg1 = new Label("Check Your Age",Label.CENTER);
private CheckboxGroup g1 = new CheckboxGroup();
private Checkbox g11 = new Checkbox("16-18",g1,false);
private Checkbox g12 = new Checkbox("19-21",g1,false);
private Checkbox g13 = new Checkbox("22-24",g1,false);
private Checkbox g14 = new Checkbox("25-44",g1,false);
private Checkbox g15 = new Checkbox("45-59",g1,false);
private Checkbox g16 = new Checkbox("Over 60",g1,false);
private double f1 = 0;
// married
private Label lg2 = new Label("Check Your Status",Label.CENTER);
private CheckboxGroup g2 = new CheckboxGroup();
private Checkbox g21 = new Checkbox("Single",g2,false);
private Checkbox g22 = new Checkbox("Married",g2,false);
private Checkbox g23 = new Checkbox("Divorced/Seperated",g2,false);
private double f2 = 0;
// Driving Record
private Label lg3 = new Label("Check Below For Record",Label.CENTER);
private Checkbox g31 = new Checkbox("Check for Accident in last
Four
Years");
private double f3 = 0;
private Checkbox g32 = new Checkbox("Check for Traffic Ticket Last
five
years");
private double f4 = 0;
// Car Type
private Label lg4 = new Label("Check Your Car Type",Label.CENTER);
private CheckboxGroup g4 = new CheckboxGroup();
private Checkbox g41 = new Checkbox("Standard",g4,true);
private Checkbox g42 = new Checkbox("Intermediate (i)",g4,false);
private Checkbox g43 = new Checkbox("High Performance (h)",g4,false);
private Checkbox g44 = new Checkbox("Sports Model (s)",g4,false);
private Checkbox g45 = new Checkbox("Premium Sports (p)",g4,false);
private double f5 = 0;
// Mile
private Label lg5 = new Label("Miles on Car",Label.CENTER);
private TextField t5 = new TextField("",10);
private double f6 = 0;
// Year
private Label lg6 = new Label("Car Year (two digits please ie
69,96,...)",Label.CENTER);
private TextField t6 = new TextField("",10);
private double f7 = 0;
// Plans
private Button b1 = new Button("Next Plan");
private Button b2 = new Button("Plan B");
// BI/PD
private Label lg7 = new Label("Combined (BI/PD)",Label.CENTER);
private TextField t7 = new TextField("",10);
private Label lg8 = new Label("Each Accid.",Label.CENTER);
private TextField t8 = new TextField("",10);
// Medical
private Label lg9 = new Label("Medical Payments",Label.CENTER);
private TextField t9 = new TextField("",10);
private Label lg10 = new Label("Each Person",Label.CENTER);
private TextField t10 = new TextField("",10);
// Comp
private Label lg11 = new Label("Comprehensive",Label.CENTER);
private TextField t11 = new TextField("",10);
private Label lg12 = new Label("Deductible",Label.CENTER);
private TextField t12 = new TextField("",10);
// Coll
private Label lg13 = new Label("Collision",Label.CENTER);
private TextField t13 = new TextField("",10);
private Label lg14 = new Label("Deductible",Label.CENTER);
private TextField t14 = new TextField("",10);
// Premium
private Label lg15 = new Label("Premium",Label.CENTER);
private TextField t15 = new TextField("",10);
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//
START HERE
public void init()
{
resize(600, 1000);
setBackground(new Color(0x99,0x55,0x99));
// THIS IS HOW TO DECLARE ONE
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
// THIS IS HOW TO ACTIVATE ONE
setLayout(gridBag);
// THESE Set a proportional space between components
// These should always be greater than zero unless you want
// Your components to crowd together
// Sun Microsystems suggest you set this at 100 and leave it
c.weightx = 1;
c.weighty = 1;
Font f = new Font("Helvetica",Font.BOLD,15);
// Set Canvas for Line
can.resize(600,5);
can.setBackground(Color.black);
// Header
// THIS IS HOW YOU PLACE A COMPONENT
// The gridx Sets the x position of the Component
// The gridy Sets the y postion of the Component
// The gridwidth Sets the number of columns this Component
will
Span
// The gridheight Sets the number of rows this component
will
span
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 6;
c.gridheight = 1;
// The anchor is used when a Component is smaller than the space (grid)
// being occupied by the Component
// It has the Following Values:
// CENTER -- the default Note: ALL UPPER CASE !
// NORTH
// NORTHEAST
// EAST
// SOUTHEAST
// SOUTH
// SOUTHWEST
// WEST
// NORTHWEST
c.anchor = GridBagConstraints.CENTER; // Example of
GridBagConstraints.anchor
// When all the Constriants are set then declare the Component
// using these Constriants
gridBag.setConstraints(title1,c); // Example of Setting
Canvas
Component to Constraints
title1.setFont(f); // Since Canvas is a
Component
you may use the setFont method
// Finally add it to the Container -- in this case The Applet's
Panel
(Parent)
add(title1);
// The rest of the Componets are attached the same way
// last name
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(l1,c);
l1.setFont(f);
add(l1);
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(t1,c);
t1.setBackground(Color.white);
t1.setFont(f);
add(t1);
// first name
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(l2,c);
l2.setFont(f);
add(l2);
c.gridx = 0;
c.gridy = 4;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(t2,c);
t2.setFont(f);
t2.setBackground(Color.white);
add(t2);
// age
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(lg1,c);
lg1.setFont(f);
add(lg1);
c.gridwidth = 1;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
g11.setFont(f);
g12.setFont(f);
g13.setFont(f);
g14.setFont(f);
g15.setFont(f);
g16.setFont(f);
c.gridx = 1;
c.gridy = 6;
gridBag.setConstraints(g11,c);
add(g11);
c.gridx = 2;
c.gridy = 6;
gridBag.setConstraints(g12,c);
add(g12);
c.gridx = 3;
c.gridy = 6;
gridBag.setConstraints(g13,c);
add(g13);
c.gridx = 4;
c.gridy = 6;
gridBag.setConstraints(g14,c);
add(g14);
c.gridx = 5;
c.gridy = 6;
gridBag.setConstraints(g15,c);
add(g15);
c.gridx = 6;
c.gridy = 6;
gridBag.setConstraints(g16,c);
add(g16);
// married
c.gridx = 0;
c.gridy = 7;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(lg2,c);
lg2.setFont(f);
add(lg2);
c.gridwidth = 1;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
g21.setFont(f);
g22.setFont(f);
g23.setFont(f);
c.gridx = 0;
c.gridy = 8;
c.gridwidth = 2;
gridBag.setConstraints(g21,c);
add(g21);
c.gridx = 2;
c.gridy = 8;
c.gridwidth = 2;
gridBag.setConstraints(g22,c);
add(g22);
c.gridx = 4;
c.gridy = 8;
c.gridwidth = 2;
gridBag.setConstraints(g23,c);
add(g23);
//Driving Record
lg3.setFont(f);
g31.setFont(f);
g32.setFont(f);
c.gridx = 0;
c.gridy = 9;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(lg3,c);
lg3.setFont(f);
add(lg3);
c.anchor = GridBagConstraints.WEST;
c.gridx = 1;
c.gridy = 10;
c.gridwidth = 6;
gridBag.setConstraints(g31,c);
add(g31);
c.gridx = 1;
c.gridy = 11;
c.gridwidth = 6;
gridBag.setConstraints(g32,c);
add(g32);
// Car type
c.gridx = 0;
c.gridy = 12;
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(lg4,c);
lg4.setFont(f);
add(lg4);
c.gridwidth = 6;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
g41.setFont(f);
g42.setFont(f);
g43.setFont(f);
g44.setFont(f);
g45.setFont(f);
c.gridx = 1;
c.gridy = 13;
gridBag.setConstraints(g41,c);
add(g41);
c.gridx = 1;
c.gridy = 14;
gridBag.setConstraints(g42,c);
add(g42);
c.gridx = 1;
c.gridy = 15;
gridBag.setConstraints(g43,c);
add(g43);
c.gridx = 1;
c.gridy = 16;
gridBag.setConstraints(g44,c);
add(g44);
c.gridx = 1;
c.gridy = 17;
gridBag.setConstraints(g45,c);
add(g45);
// Miles
c.gridx = 1;
c.gridy = 18;
c.gridwidth = 1;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
t5.setFont(f);
t5.setBackground(Color.white);
gridBag.setConstraints(t5,c);
t5.setText("0.0");
add(t5);
c.gridx = 2;
c.gridy = 18;
c.gridwidth = 4;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg5,c);
lg5.setFont(f);
add(lg5);
// Year
c.gridx = 1;
c.gridy = 19;
c.gridwidth = 1;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
t6.setFont(f);
t6.setBackground(Color.white);
gridBag.setConstraints(t6,c);
t6.setText("0.0");
add(t6);
c.gridx = 2;
c.gridy = 19;
c.gridwidth = 4;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg6,c);
lg6.setFont(f);
add(lg6);
// Line
c.gridx = 0;
c.gridy = 20;
c.gridwidth = 7;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(can,c);
add(can);
// Plans
c.gridx = 0;
c.gridy = 21;
c.gridwidth = 3;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
gridBag.setConstraints(b1,c);
b1.setFont(f);
add(b1);
c.gridx = 3;
c.gridy = 21;
gridBag.setConstraints(b2,c);
b2.setFont(f);
//add(b2);
// BI/PD
c.gridx = 0;
c.gridy = 22;
c.gridwidth = 2;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg7,c);
lg7.setFont(f);
add(lg7);
t7.setFont(f);
t7.setBackground(Color.white);
c.gridx = 3;
c.gridy = 22;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t7,c);
add(t7);
c.gridx = 4;
c.gridy = 22;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg8,c);
lg8.setFont(f);
add(lg8);
t8.setFont(f);
t8.setBackground(Color.white);
c.gridx = 6;
c.gridy = 22;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t8,c);
add(t8);
// Medical
c.gridx = 0;
c.gridy = 23;
c.gridwidth = 2;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg9,c);
lg9.setFont(f);
add(lg9);
t9.setFont(f);
t9.setBackground(Color.white);
c.gridx = 3;
c.gridy = 23;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t9,c);
add(t9);
c.gridx = 4;
c.gridy = 23;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg10,c);
lg10.setFont(f);
add(lg10);
t10.setFont(f);
t10.setBackground(Color.white);
c.gridx = 6;
c.gridy = 23;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t10,c);
add(t10);
// Comp
c.gridx = 0;
c.gridy = 24;
c.gridwidth = 2;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg11,c);
lg11.setFont(f);
add(lg11);
t11.setFont(f);
t11.setBackground(Color.white);
c.gridx = 3;
c.gridy = 24;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t11,c);
add(t11);
c.gridx = 4;
c.gridy = 24;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg12,c);
lg12.setFont(f);
add(lg12);
t12.setFont(f);
t12.setBackground(Color.white);
c.gridx = 6;
c.gridy = 24;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t12,c);
add(t12);
// Coll
c.gridx = 0;
c.gridy = 25;
c.gridwidth = 2;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg13,c);
lg13.setFont(f);
add(lg13);
t13.setFont(f);
t13.setBackground(Color.white);
c.gridx = 3;
c.gridy = 25;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t13,c);
add(t13);
c.gridx = 4;
c.gridy = 25;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg14,c);
lg14.setFont(f);
add(lg14);
t14.setFont(f);
t14.setBackground(Color.white);
c.gridx = 6;
c.gridy = 25;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t14,c);
add(t14);
// Premium
c.gridx = 0;
c.gridy = 26;
c.gridwidth = 3;
c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(lg15,c);
lg15.setFont(f);
add(lg15);
t15.setFont(f);
t15.setBackground(Color.white);
c.gridx = 6;
c.gridy = 26;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
gridBag.setConstraints(t15,c);
add(t15);
display();
} // End init()
}
//
GridBagConstraints also has a property called fill
//
the GridBagConstraints.fill property adjust how much
//
space the Component takes up within the grid
//
It has the Following Values
//
BOTH // fills the Grid
//
HORIZONTAL // Allows the Componet to fill Grid Horizontaly
//
VERTICAL // same as above except Vertical control
//
NONE // no resizing is done
//
There is an alternative to the gridy and gridx properties
//
it is called GridBagConstraints.RELATIVE
//
this allows you to by pass setting gridx and grid y
//
for each componet BUT
//
you must declare the last Component in a row with
//
GridBagConstraints.REMAINDER
//
This works fine but you do give up some control of your Components
------------------------------------------------------------------------
How
do I use grid layout?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I use grid layout?
Date:
Mon, 5 Oct 1998 06:10:51 -0500
You
use Grid Layouts for Rectangular Layouts -- mostly.
The
Grid Layout has Two construtors: GridLayout(int rows,int cols) and
GridLayout(int
rows,int cols,int hgap,int vgap). Both only allow One
Component
per Grid Space
Appet
Example
public
void init()
{
setLayout(new GridLayout(3,3)); // THE ANSWER
Button button0 = new Button("A");
add(button0);
Button button1 = new Button("A#");
add(button1);
Button button2 = new Button("B");
add(button2);
Button button3 = new Button("C");
add(button3);
Button button4 = new Button("C#");
add(button4);
Button button5 = new Button("D");
add(button5);
Button button6 = new Button("D#");
add(button6);
Button button7 = new Button("E");
add(button7);
Button button8 = new Button("F");
add(button8);
// This works for any Component ie doesn't have to be a Button
}
//
see www.nbwarner.com/applets/MusicMaker/index.html
//
for an Extended (5,5) Music Key Board
///////////////////////////////////////////////////////
////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//
The other constructor makes space between the components
//
with hgap (Horizontal) vgap (Vertical)
setLayout(new
GridLayout(6,4,4,4)); // THE SECOND ANSWER
Label
title1 = new Label("Norms",Label.CENTER);
Label
title2 = new Label("Corner",Label.CENTER);
Label
title3 = new Label("Calculator",Label.CENTER);
title1.setFont(f1);
title2.setFont(f1);
title3.setFont(f1);
add(title1);
// titles
add(title2);
add(display);
// number display
add(title3);
// and more titles
//
buttons
Button
button0 = new Button("0");
Button
button1 = new Button("1");
Button
button2 = new Button("2");
Button
button3 = new Button("3");
Button
button4 = new Button("4");
Button
button5 = new Button("5");
Button
button6 = new Button("6");
Button
button7 = new Button("7");
Button
button8 = new Button("8");
Button
button9 = new Button("9");
Button
button10 = new Button("+");
Button
button11 = new Button("-");
Button
button12 = new Button("X");
Button
button13 = new Button("/");
Button
button14 = new Button("1/x");
Button
button15 = new Button("Clear");
Button
button16 = new Button(".");
Button
button17 = new Button("=");
button0.setFont(f);
button1.setFont(f);
button2.setFont(f);
button3.setFont(f);
button4.setFont(f);
button5.setFont(f);
button6.setFont(f);
button7.setFont(f);
button8.setFont(f);
button9.setFont(f);
button10.setFont(f);
button11.setFont(f);
button12.setFont(f);
button13.setFont(f);
button14.setFont(f);
button15.setFont(f);
button16.setFont(f);
button17.setFont(f);
add(button7);
add(button8);
add(button9);
add(button13);
add(button4);
add(button5);
add(button6);
add(button12);
add(button1);
add(button2);
add(button3);
add(button11);
add(button0);
add(button16);
add(button17);
add(button10);
add(button14);
add(button15);
//
GOTO: www.nbwarner.com/applets/applet1.html and see Calculator
//
for an Example of GridLayout(x,y,m,n); Constructor
------------------------------------------------------------------------
How
do I get the author tag in JavaDoc?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I get the author tag in JavaDoc?
Date:
Tue, 6 Oct 1998 07:15:48 -0500
There
are some options available for generating
Javadoc
within the IDE of Metrowerks.
In
the settings, select Javadoc from the linker. Then
uncheck
the ignore comment check-box.
- DL
>Hi:
>I
could use the see tag in method, but i didn't get any reference in my
>html
file. About author tag and version tag i could not see anything on
>html.
Do, i have to explicitly write in html file for see tag.
>vinita
How
do I find javadoc?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I find javadoc?
Date:
Tue, 6 Oct 1998 07:28:29 -0500
For
those with a pre-3.0 version of the codeWarrior,
you
may use the computers in school or the
javadoc
command on your own machines.
Typically,
in cases such as Abrar's, I would suggest
an
upgrade, or a trip to school. Java doc is
installed
on the sun's so you can telnet in to
do
this type of work without leaving the apartment...
- DL
>Hi
Professor,
>
i am using "code worrior 2.1" and the pre-linker option from the
>"target
settings" does not have the option "javadoc prelinker" please
>tell
me how do i go about the problem. i am waiting for your reply.
>
>Abrar
>
>______________________________________________________
>Get
Your Private, Free Email at
http://www.hotmail.com
How
do I know if a class can be public?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I know if a class can be public?
Date:
Tue, 6 Oct 1998 09:43:00 -0500
The
answer to this depends on how portable
you
want to make your source code.
The
very portable answer requires that each
public
class reside in a file that has a name
which
matches the class name.
Thus:
public
class Hello {
...
}
resides
in the Hello.java file.
Only
one public class is permitted per file....
This
is not a Java requirement, but a cross-platform
tool
requirement.
When
making a single jar file for distribution, it does
not
matter.
It
also does not have to matter in codewarrior...it is
an
option in the compiler...
- DL
>Prof.
D.Lyon:
>Can
I put more than one public class in one .java file?
>I
tried to run some small java program, I have three classes in one
>.java
file, when I set all of them in public, it did not work. But when I
>set
only one class in public, it is ok. Why? How do you manage them in
>your
big 'Kahindu' project?
>
>Thank
you for your response!
>
>Regards
>-Lin
How
do I make Javadoc work on non-public files?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I make Javadoc work on non-public files?
Date:
Thu, 8 Oct 1998 09:40:09 -0500
Hi
Jijoung,
Let
me see if I can respond to your
e-mail
below:
>How
are you Professor!
>I
am jiyoung an.
>I
almost finished java CS410 assignment#4.
>I
compiled with JDK1.1.6. I think javadoc1.1.x does not work for documenting
>inner
clases.
Yes,
this is a feature!
Javadoc1.1.6 which I used didn't work with two of my source
>files
which are gui/Cshort.java gui/Doable.java. Other source file's no
>problem.
Are these -Cshort.java and Doable.java- inner classes?
No.
>How
do I
>make
javadoc with these two files?
They
are not public. You can change the javadoc flags to
output
non-public files, or you can make them public....
For
example:
package
gui;
interface
Doable {
public void doit(double a[]);
}
//goes
to:
package
gui;
public
interface Doable {
public void doit(double a[]);
}
OK?
- DL
>I
got 4 source files from you for assignment. Two files work fine. so I put it
>on
my web page ( www.bridgeport.edu/~jiyoung/java410.html)
>
>Thanks
>Jiyoung
An
How
do you set alarms in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do you set alarms in Java?
Date:
Thu, 8 Oct 1998 09:56:47 -0500
The
easier techniques for doing this are described
in
my book. See page 99 for putting a thread
to
sleep....It will wake anytime you say...
JNI
and Java Direct both permit the invocation
of
native methods from Java....
- DL
>Dr.
Lyon:
>
>I
could not find any kind of alarm or timer class in Java packages. Normally
>in
any language we can set an alarm for specific number of msec and install
>an
alarm event handler, when the time lapses the OS will interrupt and call
>our
event handler. So, I would expect to find a wrapper for this behavior in
>any
language, but I cannot find it in Java.
>
>Another
question, if a language lacks some functionality it is normally
>allowed
to embed some other language or use an OS API (i.e. we can use Win32
>API
in Visual Basic). How can I use a Win32 API in Java? Or, how can I load
>dynamic
link libraries in Java (since all APIs are exported through DLLs)?
>
>Thank
for your help
>Regards
>Alex
How
do I draw BNF Diagrams?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I draw BNF Diagrams?
Date:
Thu, 8 Oct 1998 09:57:55 -0500
>Date:
Mon, 05 Oct 1998 10:27:36 +0100
>From:
guyot@cui.unige.ch (Jacques Guyot)
>Subject:
Re: BNF Diagrams
>X-Sender:
guyot@uni2a.unige.ch
>To:
"Dr. Douglas Lyon" <lyon@snet.net>
>MIME-version:
1.0
>
>
>Hello
>
>We
are working on new version of HyperGOS,
>you
can try this version at:
>
>http://cuiwww.unige.ch/db-research/Enseignement/analyseinfo/DIAG33JAVA/index
>.html
>
>If
you have comments or sugestions about this, your are welcome.
>
>Thanks
>
>
>>Dear
Jacques,
>>I
am very interested in generating BNF expression diagrams using
>>the
automated tools used in the
>>BNF
Web Club Language. Can you give me a pointer
>>to
the tools so that I can generate my own?
>>
>>Thanks!
>>
>>Regards,
>>
- Doug Lyon
>
How
do I do implicit threading?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I do implicit threading?
Date:
Thu, 8 Oct 1998 12:54:25 -0500
Implicit
threads are available in the AWT...
just
call repaint, after the paint. This will
schedule
a call to update in so many
milliseconds....
Try
the following code and see:
- DL
import
java.awt.*;
import
java.awt.image.*;
public
class DrawPoints extends Frame {
int xsize,ysize,xcenter,ycenter;
int delay=10;
int numberOfPoints=1000;
Graphics backGC;
Image backBuffer;
int[] starX,starY,starZ;
Color[] grayScale;
public static void main(String args[]) {
DrawPoints f = new DrawPoints();
f.setSize(256,256);
f.show();
f.init();
f.repaint();
}
public void init()
{
//Get screen dimensions
xsize=size().width;
ysize=size().height;
xcenter=xsize/2;
ycenter=ysize/2;
//Init double-buffering
backBuffer = createImage(xsize, ysize);
backGC = backBuffer.getGraphics();
starX=new int[numberOfPoints];
starY=new int[numberOfPoints];
starZ=new int[numberOfPoints];
double theta = 0;
double eps = (1.0/numberOfPoints) * 2*Math.PI;
for (int n=0;n<numberOfPoints;n++) {
starX[n]=(int)
((Math.sin(theta)*xsize*2.0)-xsize/2);
starY[n]=(int)
((Math.cos(theta)*ysize*2.0)-ysize/2);
starZ[n]=(int)
(Math.random()*4095);
theta = theta + eps;
}
//Create grayscale tones
grayScale=new Color[256];
for (int n=0;n<256;n++)
grayScale[255-n]=new Color(n,n,n);
}
public void paint(Graphics g)
{
//Clear screen
backGC.setColor(Color.black);
backGC.fillRect(0,0,xsize,ysize);
for (int n=0;n<numberOfPoints;n++)
{
//Move stars and clip against viewplane
//The back clipping plane and the
// view plane are hard coded
//for optimizing reasons.
// Viewplane=512, backplane=4095
starZ[n]-=50;
if (starZ[n]<512) starZ[n]=4095;
int z=starZ[n];
//Apply perspective projection
int x=(starX[n]<<9)/z+xcenter;
int y=(starY[n]<<9)/z+ycenter;
//Apply dept shading
backGC.setColor(grayScale[z>>4]);
//Draw star
backGC.drawLine(x,y,x,y);
}
//Draw buffer to screen
g.drawImage(backBuffer, 0, 0, this);
repaint(50,0,0,256,256);
}
public void update(Graphics g) {
paint(g);
}
}
How
do I buffer output in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I buffer output in Java?
Date:
Wed, 21 Oct 1998 08:50:50 -0400
The
following code is an example
of
buffered output in Java:
import java.io.*;
public class fastout {
public static void main(String args[])
{
FileOutputStream fdout =
new FileOutputStream(FileDescriptor.out);
BufferedOutputStream bos =
new BufferedOutputStream(fdout, 1024);
PrintStream ps =
new PrintStream(bos, false);
System.setOut(ps);
final int N = 100000;
for (int i = 1; i <= N; i++)
System.out.println(i);
ps.close();
}
}
How
do you uncompress a Jar file?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do you uncompress a Jar file?
Date:
Tue, 15 Sep 1998 05:29:32 -0500
To
uncompress a Jar file,
you
can use two techniques:
On
Solaris use:
comm.jar
devil{lyon}56:
jar -xvf comm.jar
extracted: META-INF/MANIFEST.MF
created: javax/
created: javax/comm/
extracted: javax/comm/CommApiVersion.class
...
On
a platform with codewarrior, you may use an
application
called the "ClassWrangler". Just open
the
file with the ClassWrangler, then drag the contents
of
the window out to the target folder.
- DL
>Date:
Mon, 14 Sep 1998 16:17:42 -0400 (EDT)
>From:
Kelvin Chew <kelvin@bridgeport.edu>
>X-Sender:
kelvin@devil
>To:
"Dr. Douglas Lyon" <lyon@snet.net>
>Subject:
Re: CPE471 HW1
>MIME-Version:
1.0
>
>Hi
Prof.,
>
>I
dragged the jar file into the project window. But as I tried to compile
>it,
I got the error message that the zip file "comm.jar" is "compressed,
>and
cannot be used", followed by some errors related to the javax package.
>Should
I decompress the jar file? How?
>
>I
put the three files (comm.jar, win32com.dll and javax.comm.properties)
>under
the folder Metrowerks/CodeWarrior/bin. Is that the right way?
>
>Thanks
for your help.
>Kelvin
>
>>
Hi Kelvin,
>>
You must drag the jar file into the project window.
>>
Then it should find it.
>>
Regards,
>>
- DL
>>
>>
>Hi Prof.,
>>
>
>>
>I tried to compile the SimpleWrite code using CodeWarrior under WinNT, and
>>
>I got the "package not found" error. Where do I change the classpath (in
>>
>what file and folder?) to make the code compiled? Thanks for your help.
>>
>
>>
>
>>
>Yours sincerely,
>>
>Kelvin Chew
>>
>>
>>
>
How
do I run an application with codewarrior?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I run an application with codewarrior?
Date:
Wed, 16 Sep 1998 07:46:32 -0500
To
run an application with
codewarrior:
1.
Start CodeWarrior.
2.
file>New Project ...
Select: Java>application, OK
Type a project name (any name is OK).
3.
In the project window, select run.
This
will compile and run the TrivialApplication
and
print "hello world!".
Good
luck!
- DL
>From:
"Service" <service@webmeridian.com>
>To:
<lyon@snet.net>
>Subject:
Fw: Frustrating with Code Warrior 3.0
>Date:
Wed, 16 Sep 1998 00:12:00 -0400
>X-MSMail-Priority:
Normal
>X-Priority:
3
>MIME-Version:
1.0
>
>
>Hi
Dr. Lyon:
>
>It's
12am Wed. and I'm trying out the stupid Metrowerks CodeWarrior 3.0 for
>the
first time trying to hand in your HW2 by today if I'm still awake. I
>made
a new apps. called TrivialApplication (the default apps. with Hello
>World)
and ran it. This is the error I'm getting right from the box:
>
>ERROR:
Could not execute TrivialApplication: The system cannot find the
>file
specified.
>
>I
made a project folder called foo where TrivialApplication is residing and
>have
it at c:\foo.
>
>I've
no clue what this means. I went to set Java Target as
>TrivialApplication
with the extension .java. Do you happen to have any
>clue?
I think I need more support on this because this is my first time
>writing
a Java stand-alone apps (not applet for I've no problem compiling
>that).
By the what are your office hours? I do need your help during the
>late
afternoon when I return from work. I will have lots of questions. I
>appreciate
your help otherwise I'll be sitting here staring at the stupid
>CodeWarrior.
>
>Frustrating,
>
>Yin
Leong
>
How
do I add jars to my class path?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I add jars to my class path?
Date:
Wed, 16 Sep 1998 07:58:34 -0500
To
add a library to your class path, place
the
library in a directory (call it Jars if you like),
then
modify the classpath variable:
setenv
CLASSPATH /home/lyon/jars/comm.jar
setenv
CLASSPATH ${CLASSPATH}:/usr/lib/java/lib/
setenv
CLASSPATH ${CLASSPATH}:.
If
you get an import error, echo the classpath:
devil{lyon}41:
echo $CLASSPATH
/home/lyon/jars/comm.jar:/usr/lib/java/lib/:.
Thanks!
- DL
How
do I compile diffcad?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I compile diffcad?
Date:
Wed, 16 Sep 1998 14:01:03 -0500
To
compile the code known as Diffcad
(from
the book, Java Digital Signal Processing)
gunzip
the sofware and untar into a directory.
Then
use javac.
For
example:
vinny.bridgeport.edu{lyon}6:
javac Diffcad.java
vinny.bridgeport.edu{lyon}7:
ls
Diffcad.class
VS/ grapher/ images/ observers/
Diffcad.java
foo.html gui/ lyon/ solid/
StringUtil/
futils/ htmlconverter/ net/ threads/
vinny.bridgeport.edu{lyon}8:
echo $CLASSPATH
/usr/lib/java/lib/classes.zip:.
vinny.bridgeport.edu{lyon}9:
- DL
>Dear
Professor Douglas A. Lyon, Ph.D.,
>
>Thank
you for your very quickly replay, I downloaded the files where you
>said
to me that I can find them. I alsof made a hardcopy of de 2 readme
>files.
I restorded the tar-file on my server ( Workstation Digital 433-au).
>I
get the diffcad.class file working. but the rest of the class files will
>not
work.
>
I get the following message : Can't find class -name of classfile -.
>
>I
changed the permisions of the sub directories under source, but no change.
>
>I
have done I java compiling whit JAVAC, still no change.
>
>What
is my problem, should I make I jar-file and change the
>classpath-envoriment.
>
>Can
you help me?
>Greetings,
>
>
>Beste
Groeten,
>
__________________________________________________________________
>|
Ind. Renaat GOBBIN |phone: +32-11-26 82 71 |
>|
Dept. WNI - Natuurkunde |fax: +32-11-26 82 99 (sekr.) |
>|
LUC-Limburgs Universitair Centrum|email: rgobbin@luc.ac.be |
>|
Universitaire campus - Gebouw D |url:
http://pdnweb.luc.ac.be/|
>|
B-3590 Diepenbeek, Belgium |Place office : Room G6 |
>|
url:
http://www.luc.ac.be/
| |
>|__________________________________|_______________________________|
How
do I pack an Array of bytes?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How to I pack an Array of bytes?
Date:
Wed, 16 Sep 1998 14:08:32 -0500
To
convert an array of int into an array of
bytes,
assuming that you only want the least
significant
8 bits in the int array, use:
byte
[] int2byte(int ints[]) {
byte b[] = new int[ints.length];
for (int i=0; i < ints.length; i++)
b[i] = (byte)ints[i];
return b;
}
>Dr
Lyon,
>Inside
the MRJClasses.zip file (which I've unzipped to analyze)
>is
sun.io.charToByteMacTEC.class which is a subclass of
>sun.io.charToByteConverter.
>This
strikes me as something we want to use to talk to the Turntable.
>Yes?No?
>Allan
How
do I playback quicktime movies in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I playback quicktime movies in Java?
Date:
Thu, 17 Sep 1998 09:06:41 -0500
>
you must use the Java plug-in from Sun to get playback in browsers w/QTJ.
>
(it will make your life easier writing applets in other ways, also)
>
>
so (i) QTW3.0.2, (ii) QTJ & (iii) Java Plug-in 1.1.2(?) for applet
>
playback
>
How
do I set the com port?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I set the com port?
Date:
Thu, 17 Sep 1998 09:10:07 -0500
To
set the com port
from
a sun to a mac,
remove
the comments from
the
line
// if (portId.getName().equals("COM2")) {
and comment out the next line, with the "/dev/a" stuff in it.
The
PC uses COM2, the sun uses /dev/a
- DL
How
do I copy a file in Java?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I copy a file in Java?
Date:
Fri, 18 Sep 1998 07:25:13 -0500
import java.io.*;
public class FileCopy {
public static void copy(String from, String to)
throws IOException
{
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
final int BUFSIZ = 1024;
byte buf[] = new byte[BUFSIZ];
int len = 0;
while ((len = fis.read(buf)) > 0)
fos.write(buf, 0, len);
}
finally {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
}
public static void main(String args[])
{
// do many invalid copy() operations
for (int i = 1; i <= 5000; i++) {
try {
copy("xxx.txt", ".");
}
catch (IOException e) {
}
}
// do a valid operation
try {
copy("xxx.txt", "yyy.txt");
}
catch (IOException e) {
System.err.println(e);
}
}
}
How
do I install Java programs on Solaris/win95/winnt?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I install Java programs on Solaris/win95/winnt?
Date:
Mon, 21 Sep 1998 09:41:21 -0500
Java
check is software that
help
check the portability of your Java.
Interestingly,
it comes with instructions for installation
on
a variety of platforms.
This
worth looking at for
an
installation of any Java software under JDK.
- DL
Solaris
1.Change
the current directory to the directory that contains the
application
you wish to examine.
2.Execute
the JavaCheck command (from the JavaCheck bin directory):
%
mypath/JavaCheck/bin/JavaCheckV
mypath
indicates the pathname for the JavaCheck distribution directory.
3.If
this doesn't run successfully, unset your CLASSPATH environment
variable
and type JavaCheck again:
%
unsetenv CLASSPATH
%
mypath/JavaCheck/bin/JavaCheckV
Windows
NT
1.Double-click
the System icon inside the Control Panel. When the System
Properties
dialog box opens, place the following variables in the lower
list
box, which is labeled User Variables. (Be careful not to change your
system
environment variables, which appear in the upper list box.)
JDKHOME
C:\JDK1.x.x
JAVACHECKHOME
C:\JavaCheck
CLASSPATH
.;%JDKHOME%\lib\classes.zip
PATH
%PATH%;%JDKHOME%\bin;%JAVACHECKHOME%\bin
These
settings assume that you have installed both the JDK and the
JavaCheck
on drive C. Substitute the correct version of the JDK you are
using
for the JDKHome value JDK1.x.x.
If
either the JDK or JavaCheck are installed on a different drive,
substitute
that drive's designator wherever it is appropriate.
2.From
the Windows Start menu or from the Control Panel, open a console
(MS-DOS-style)
window.
3.In
the console window, change the current directory to the directory that
contains
the application you wish to examine.
4.Execute
the JavaCheck command:
JavaCheckV
This
will run the visual tool version of JavaCheck.
Windows
95
1.Edit
the system's AUTOEXEC.BAT file and add the following environment
variable
settings:
set
JDKHOME=C:\JDK1.x.x
set
JAVACHECKHOME=C:\JavaCheck
set
PATH=%PATH%;%JAVACHECKHOME%\bin
These
settings assume that you have installed both the JDK and the
JavaCheck
on drive C. Substitute the correct version of the JDK you are
using
for the JDKHOME value JDK1.x.x.
If
either either the JDK or JavaCheck are installed on a different drive,
substitute
that drive's designator wherever it is appropriate. 2.Perform
steps
2 through 4 of the instructions listed under Windows NT. 3.If you
encounter
an "Out of environment space" error, then you'll need to increase
the
size of the environment table. You can do this at the command line
(which
is temporary) or by editing a configuration file to make a permanent
change
(which requires restarting your computer).
To
temporarily increase environment space, enter the following at the DOS
prompt:
command
/e:8192
To
permanently increase environment space, add the following line to your
CONFIG.SYS
file and then restart your system:
shell=command.com
/e:8192 /p
Once
you've increased the size of the environment table, try running
JavaCheck
again.
How
do I update codewarrior?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I update codewarrior?
Date:
Thu, 24 Sep 1998 05:49:33 -0500
Version
3.1 update for windows is at:
http://www.metrowerks.com/db/updates.qry?function=detail&updates_uid=199
Version
3.1 update for mac is at:
http://www.metrowerks.com/db/updates.qry?function=detail&updates_uid=198
- DL
How
do I add features to a class?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I add features to a class?
Date:
Fri, 25 Sep 1998 10:05:00 -0500
To
add features to a class, you
do
not need to modify a class.
The
procedure is to extend the class.
Thus,
you are to write:
public
class ModifierFrame extends ShortCutFrame {
...
}
You
print the ModifierFrame...not the ShortCutFrame.
An
instance of the ModifierFrame should have the ability to
handle
the control and alt character....
One
way to approach this problem is by overloading the alt
method.
Regards,
- DL
>Professor,
I am still not clear about ypur homework. I am not sure what
>you
want us to do. modify your program?
>I
run your program kahindu, which already include some keyboard shortcut.
>If
to modify your program, do we have to print all the program including
>your
program plus modified part for homework?
>
>could
you just explain it fully?
>
>Thank
you very much!
>
>xwan
How
do I find Kahindu?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I find Kahindu?
Date:
Fri, 25 Sep 1998 10:05:00 -0500
Kahindu
is available from:
ftp://vinny.bridgeport.edu/pub/ipij
- DL
>Hi!
Prof.
>
>I
am not been able check Kahendu.
>When
I click on Kahendu error message appear on screen like:
>
>Netscape
is unable to locate the server pub
>The
server does not have DNS enty.
>Check
the server name in the locatiopn URL and try again.
>
>Now
what should I Do?
>
>thanks
>
>shobhna
>
>______________________________________________________
>Get
Your Private, Free Email at
http://www.hotmail.com
How
do you determine a key-code?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do you determine a key-code?
Date:
Mon, 28 Sep 1998 13:04:42 -0500
To
determine a keycode, just
print
the keyevent using System.out.println.
Regards,
- DL
>Could
you tell me the ASCII or UNICODE for alt and ctrl?
>
I think we need it to do the petriMap function , right?
>
>
>xwan
How
do I figure out what modifiers are pressed?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I figure out what modifiers are pressed?
Date:
Mon, 28 Sep 1998 21:18:54 -0500
The
InputEvent class has several modifier masks you
can
use to test for keys:
public
abstract class InputEvent extends ComponentEvent {
/**
* The shift key modifier constant.
*/
public static final int SHIFT_MASK = Event.SHIFT_MASK;
/**
* The control key modifier constant.
*/
public static final int CTRL_MASK = Event.CTRL_MASK;
/**
* The meta key modifier constant.
*/
public static final int META_MASK = Event.META_MASK;
/**
* The alt key modifier constant.
*/
public static final int ALT_MASK = Event.ALT_MASK;
/**
* The mouse button1 modifier constant.
*/
public static final int BUTTON1_MASK = 1 << 4;
/**
* The mouse button2 modifier constant.
*/
public static final int BUTTON2_MASK = Event.ALT_MASK;
/**
* The mouse button3 modifier constant.
*/
public static final int BUTTON3_MASK = Event.META_MASK;
When
trying to figure out which key does what...
use:
public void keyTyped (KeyEvent e) {
System.out.println(e);
int key = e.getKeyChar();
System.out.println("keycode="+key+
" hex="+ Integer.toString(key,16));
int mods = e.getModifiers();
System.out.println("mods="+mods+
" hex="+ Integer.toString(mods,16)
+" keyText="+e.getKeyText(key));
}
To
help...
- DL
>>
Hello everyone
>>
I was working on the HW3 for java and have designed the petrinet and petri
>>
table for implementing the additional Control and Alt keys in the menu.
>>
The problem is that when i use the Keypressed method it returns a zero
>>
value for both the Control and Alt key. The control key with a
>>
combination of another key returns a valid unique int value and hence i
>>
can check on the ctrl+key combination. Hence i can check if the control
>>
key is pressed if the returned value is withen a specific range or not.
>>
But the combination of an Alt key with any other non modifier returns a
>>
zero value. So how will i trap or know that an Alt key combination has
>>
been pressed.
>>
I have also tried the KeyTyped method under the awt events and too returns
>>
a zero.
>>
thanks
>>
>>
Leonard Francis
>>
mailto:FrancisL@flexi.com
>>
>>
How
can I obtain a consistent keyboard mapping?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How can I obtain a consistent keyboard mapping?
Date:
Tue, 29 Sep 1998 04:18:26 -0500
One
approach to obtaining a mapping between
keystrokes
and the integer value of the
keys
is to create an array of strings.
The
index into the string is the key number and the
value
of the string is the short-cut representation.
For
example:
"^-A",
should represent control-A
- DL
>Hi
Professor,
>
I am having some problem with the Alt and Ctrl values.I have used
>e.getKeyChar
to fine out the int value of those keys. I used the value from
>the
source code but when I execute it gives 0 for both keys. Can u help me
>with
>this.
>
>Rajendra
Maharjan
How
can I print all the key-event info?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How can I print all the key-event info?
Date:
Tue, 29 Sep 1998 04:47:44 -0500
public
void keyPressed(KeyEvent evt)
{
System.out.println("KeyPressed,
consumed: "+evt.isConsumed()+" src is:
"+evt.getSource()+"
id: "+evt.getID()+", code:
"+evt.getKeyCode()+"("+evt.getKeyText(evt.getKeyCode())+"),
char:
"+(int)evt.getKeyChar()+",
modifiers:
"+evt.getKeyModifiersText(evt.getModifiers()));
How
do I get tech-support from Metrowerks?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I get tech-support from Metrowerks?
Date:
Wed, 30 Sep 1998 06:12:00 -0500
To
get tech support on a metrowerks product
you
purchased (and I suggest this only in the case
when
I have no idea why things are going wrong)...
Use:
support@metrowerks.com
Be
sure to fill out the support form that came
with
your product, including the serial number.
Sorry
I don't know the answer to the below question.
Perhaps
a reinstallation?
- DL
>Hi
Dr. Lyon,
>
>I
just try to generate document for a simple example by Codewarrior, but
>the
error message is:
>
>Link
Error : Couldn't find Sun JDK or JRE (see release notes for details)
>
>I
have already configure Pre-linker as "JavaDoc Pre-linker". Could you
>tell
me how to fix this problem?
>
>Thanks
>Chen
How
do I run Java using CGI?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I run Java using CGI?
Date:
Wed, 30 Sep 1998 06:59:39 -0500
Try
http://www.bridgeport.edu/~lyon/cgi-bin/run.cgi
You
all should have access to:
/home/lyon/.public_html/cgi-bin/hello
See
if you can get this to work in your home directory.
- DL
In
the directory:
/home/lyon/.public_html/cgi-bin
in
the file:
run.cgi
Place
the following code:
#!/bin/sh
echo
Content-type: text/html
echo
echo
"<HTML><HEAD>"
echo
"<TITLE>Running Java"
echo
"</TITLE></HEAD>"
echo
"<BODY>"
echo
"Java output follows"
echo
"<hr>"
echo
"<h2><center>"
/usr/local/jdk/bin/java
hello
echo
"</center></h2>"
echo
"<hr>"
echo
"</BODY></HTML>"
Then:
chmod
+x run.cgi
Make
sure that the hello.class file is present:
ls
hello/
run.cgi* sysinfo.cgi*
hello.class
run.cgi~* sysinfo.cgi~*
Here
is the hello.java class:
public
class hello {
public
static void main(String args[]) {
for(int
i=0; i < 10; i++)
System.out.print(i+" ");
}
}
- DL
>please
find attached the file containing the script that you mailed to me.
>i
just changed the cat command to uname and so prints either roadrunner,
>egypt,
devil, stargazer or whatever machine. i am not too sure both
>suppose
this is what you wanted. you can just run it from the command line
>and
see it even without a browser.
>/~~~\___/~~~\___/~~~\___/~~~\___/~~~\___/~~~\___/~~~\___/
>computers
are very stupid, they can only give you answers
>^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>olumide
mark adebayo
>contact:-
>
150 marina park street
>
apt 227, bridgeport, ct 06604-5616
>
203-576-2027
>
olumide@bridgeport.edu
>
http://www.bridgeport.edu/~olumide
>
>
>
>
>Content-Type:
TEXT/PLAIN; charset=US-ASCII; name="sysinfo.cgi"
>Content-ID:
<Pine.GSO.4.04.9809291605370.21472@devil>
>Content-Description:
sysinfo.cgi
>Content-Disposition:
attachment; filename="sysinfo.cgi"
>
>Attachment
converted: RAM Disk:sysinfo.cgi (TEXT/MSIE) (00000013)
How
do I design my programs?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I design my programs?
Date:
Wed, 30 Sep 1998 07:09:22 -0500
Typically
there is more than one way
to
design a program. You may use
any
technique that works. I only explain those
techniques
that I have tried myself.
Let
me encourage you to explore the Java
technology
to its fullest.
Regards,
- DL
>Hi
Dr. Lyon:
>
>Do
I have to use Key Mapping at all? You have that class commented out in
>ShortCutFrame.java
and hence, I assume we don't need it. I believe it's
>just
cosmestic right. I'm just printing the UNICODE using e.getKeyCode() in
>integers.
But, I do use IsCTRL() and IsAlt() to trap those UNICODE numbers.
>
>Yin
Leong
>
>----------
>From:
Dr. Douglas Lyon <lyon@snet.net>
>To:
cs410x-list@vinny.bridgeport.edu
>Subject:
Does Java give ASCII Keycodes?
>Date:
Tuesday, September 29, 1998 5:55 AM
>
>No,
Java uses UNICODE.
>To
perform this mapping, you may like to consider
>writing
a program that generates the Java needed to
>create
the array. I suggest this because the
>alternative
appears to be to run the program
>and
write the mapping by hand.
>
>Regards,
>
- DL
>
>>Hi
Dr.Lyon:
>>
>>I'm
not sure what other students are facing. The following is what I'm
>>finding
out:
>>
>>1.
When using e.getKeyChar(), v gives 118 and V gives 86 but CTRL-v or
>>CTRL-Shift-v
gives 22. I realize that with the CTRL key, the result is 118
>>-
96 = 22. That 96 somehow has to do with CTRL. For e or E gives 101.
>>CTRL-e
or CTRL-E gives 5, which is 101 - 96 = 5. Try CTRL-4 (any
>>non-letter)
and you'll get 0. Strange!
>>
>>2.
As for Alt-c, you get 99 (same as c itself). How the world one can
>>detect
Alt? Moreover, when I hit Alt-any non-modifier, the JView hangs up
>>and
is not willing to take any keystroke until I move the window focus to
>>the
Win 95 desktop and go back into JView window. I'm not sure whether
>this
>>is
true in Unix or Mac.
>>
>>3.
Now when I use e.getKeyCode(), I cannot get lower case letter at all.
>>Lower
case on the keyboard gives upper case in the integer result.
>>Moreover,
hitting CTRL-c is now become CTRL (17) and then C (99) - not 3.
>>Why?
I prefer using e.getKeyCode() then because I can separately identify
>>the
modifier and non-modifier. But, I won't be able to use lower case
>>letter.
>>
>>So
should we use e.getKeyCode() or e.getKeyChar()? If we had to use
>>e.getKeyChar(),
maybe we would hand in HW3 next year or until Scott
>McNealy
>>(CEO
of Sun) figures out how to use ASCII coding.
>>
>>Sincerely,
>>
>>Yin
Leong
>>
>>
>>----------
>>From:
Xiang Wan <xwan@bridgeport.edu>
>>To:
cs410x-list@vinny.bridgeport.edu
>>Subject:
Re: FW: Need help
>>Date:
Monday, September 28, 1998 3:54 PM
>>
>>changed
getKeyChar () to getKeyCode()
>>
>>xwan
How
do you account for PEER classes?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do you account for PEER classes?
Date:
Wed, 30 Sep 1998 07:13:58 -0500
Peer
classes are the interface between the operating
system
subroutines and the Java AWT. This
substrate
is used to make Java more portable between
platforms.
Their implements are left
to
large libraries (like x-windows, on a sun) which
give
us the Dialog boxes and Frames...
Regards,
- DL
>Dr.
Lyon:
>
>I
see that almost all visual AWT classes deal with something called peer,
>and
there is a peer package where all the classes are repeated but they have
>all
but no code. Can you, please, explain what all this peer stuff is about?
>
>Here
is an example that you can find in java.awt.Dialog.java:
>
>/**
>
* Creates the dialog's peer. The peer allows us to change the
>appearance
>
* of the frame without changing its functionality.
>
* @since JDK1.0
>
*/
>
public void addNotify() {
>
if (peer == null) {
>
peer = getToolkit().createDialog(this);
>
}
>
super.addNotify();
>
}
>
>
>Regards
>Alex
How
do I describe a problem to get help?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
How do I describe a problem to get help?
Date:
Wed, 30 Sep 1998 07:16:28 -0500
In
order to describe a problem so that you
can
get help, you must include at least some of the
error
message...
For
example,
"but
still having some probelm
>executing
it."
Could
mean:
1.
It does not compile
2.
It throws an exception
3.
It prints wrong output
4.
....
Without
the specific detail, I cannot guess at a solution.
Regards,
- DL
>Hi
Prof.
>i'm
also having a simliar problem getting the values of Alt and Ctrl.
>i've
tried using both e.getKeyChar() and e.getKeyCode but still having
>some
probelm
>executing
it.
>
>sushil
gurung
>
>Rajendra
Maharjan wrote:
>
>>
Hi Professor,
>>
I am having some problem with the Alt and Ctrl values.I have used
>>
e.getKeyChar to fine out the int value of those keys. I used the value from
>>
the source code but when I execute it gives 0 for both keys. Can u help
>>me
with
>>
this.
>>
>>
Rajendra Maharjan
How
do you run a makefile?
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
[CS410X] How do you run a makefile?
Date:
Wed, 22 Apr 1998 13:23:28 -0400
One
students writes:
>Dear
Prof. Lyon,
>
>I
have trouble to make it run. I have no idea how to do it?
>
>
>
>jordan%
Makefile
>Makefile:
Permission denied
To
run a make file type:
make
If
there is a command in the make, it will appear
in
the Makefile itself. For example, in one make file
we
see:
>comp:
# co $(SRC)
>
javac -d ~/classes $(SRC) # rcsclean docs: # co -kv $(SRC)
>
chmod u+w $(SRC)
>
mv $(SRC) ..
Therefore
type:
make
comp
This
will invoke the javac on the $(SRC) and place
the
classes in your ~/classes directory (which must exist!)...
- DL
How
to display an image (sequence)
From:
"Dr. Douglas Lyon" <lyon@snet.net>
Subject:
[CS410X] How to display an image (sequence)
Date:
Mon, 16 Mar 1998 07:15:43 -0400
import
java.awt.*;
import
java.applet.Applet;
import
java.net.*;
/*
* This applet displays an image sequence (gif animation)
*/
public
class ImageDisplay extends Applet {
Image image;
URL url; // location of the image
public void init() {
try {
url = new URL(
"http://lyon.bridgeport.edu/cpe210/kmaps/k1.gif");
}
catch (MalformedURLException e)
{e.printStackTrace();}
image = getImage(url);
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
[CS411X]
CS588x Lect 4 Code Example How do I move Components?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
19 Feb 1999 08:07:25 -0500
import
java.awt.*;
import
java.awt.event.*;
public
class Main extends Frame {
CheckboxMenuItem
testCB = new CheckboxMenuItem("Test");
Main()
{
super("Container
Example");
MenuBar
mb = new MenuBar();
ActionListener
actionListener = new ActionEventHandler();
MouseEventHandler
mouseListener = new MouseEventHandler();
//
Initialize Edit Menu
Menu
m = new Menu("Edit");
m.add("Remove
All");
testCB.addItemListener(new
ItemEventHandler());
m.add(testCB);
mb.add(m);
m.addActionListener(actionListener);
//
Initialize Add Menu
m
= new Menu("Add");
m.add("java.awt.Button");
m.add("java.awt.Checkbox");
m.add("java.awt.Choice");
m.add("java.awt.List");
m.add("java.awt.MenuItem");
m.add("java.awt.Scrollbar");
m.add("java.awt.TextArea");
m.add("java.awt.TextField");
m.add("java.awt.Panel");
m.add("OvalComponent");
m.add("RectangleComponent");
m.add("TriangleComponent");
mb.add(m);
//
Set the menubar.
setMenuBar(mb);
//
Listen for events.
m.addActionListener(actionListener);
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
//
Remove the default layout manager.
setLayout(null);
setSize(400,
200);
show();
}
Component
dragging;
Component
stretching;
Point
offset;
class
MouseEventHandler extends MouseAdapter
implements
MouseMotionListener {
public
void mousePressed(MouseEvent evt) {
int
x = evt.getX();
int
y = evt.getY();
Component
c = getComponentAt(x, y);
if
(c != null && c != Main.this) {
if
(evt.isShiftDown() && evt.isControlDown()) {
remove(c);
}
else if (evt.isAltDown()) {
stretching
= c;
//
Bring to front.
remove(c);
add(c,
0);
}
else {
offset
= new Point(x-c.getLocation().x,
y-c.getLocation().y);
dragging
= c;
//
Bring to front.
remove(c);
add(c,
0);
repaint();
}
}
}
public
void mouseReleased(MouseEvent evt) {
stretching
= dragging = null;
}
public
void mouseDragged(MouseEvent evt) {
int
x = evt.getX();
int
y = evt.getY();
if
(dragging != null) {
dragging.setLocation(x-offset.x,
y-offset.y);
}
else if (stretching != null) {
stretching.setSize(x-stretching.getBounds().x,
y-stretching.getBounds().y);
}
}
public
void mouseMoved(MouseEvent evt) {
}
}
int
newX, newY;
class
ActionEventHandler implements ActionListener {
public
void actionPerformed(ActionEvent evt) {
newX
= Math.max(getInsets().left, newX);
newY
= Math.max(getInsets().top, newY);
Component
c = null;
String
arg = evt.getActionCommand();
try
{
Class
cl = Class.forName(arg);
c
= (Component)cl.newInstance();
add(c);
Dimension
d = c.getPreferredSize();
c.setBounds(newX,
newY, d.width, d.height);
c.setEnabled(testCB.getState());
newX
+= 20;
newY
+= 20;
if
(newX > getSize().width*3/4)
newX
= 0;
if
(newY > getSize().height*3/4)
newY
= 0;
}
catch
(Exception e) {
//System.out.println(e);
}
repaint();
}
}
class
ItemEventHandler implements ItemListener {
public
void itemStateChanged(ItemEvent evt) {
Component[]
all = getComponents();
boolean
newState = (evt.getStateChange() == ItemEvent.SELECTED);
//
Enable all the components.
for
(int i=0; i<all.length; i++) {
all[i].setEnabled(newState);
}
}
}
static
public void main(String[] args) {
System.out.println("hello");
new
Main();
}
}
class
OvalComponent extends Component
implements
FocusListener {
boolean
hasFocus;
OvalComponent()
{
//
Listen for focus events.
addFocusListener(this);
setSize(80,
80);
}
public
void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(0,
0, getSize().width-1, getSize().height-1);
}
public
Dimension getPreferredSize() {
return
getSize();
}
public
boolean isFocusTraversable() {
return
true;
}
public
boolean contains(int x, int y) {
int
midX = getSize().width/2;
int
midY = getSize().height/2;
//
This formula doesn't really work for ovals.
return
(midX-x)*(midX-x) + (midY-y)*(midY-y) <= midX*midX;
}
public
void focusGained(FocusEvent evt) {
hasFocus
= true;
repaint();
}
public
void focusLost(FocusEvent evt) {
hasFocus
= false;
repaint();
}
}
class
TriangleComponent
extends
OvalComponent {
public
void paint(Graphics g){
g.setColor(Color.blue);
Polygon
p
=
new Polygon();
p.addPoint(0,0);
p.addPoint(getSize().width,
0);
p.addPoint(getSize().width/2,
getSize().height);
p.addPoint(0,0);
g.fillPolygon(p);
}
}
class
RectangleComponent
extends
OvalComponent
implements
FocusListener {
public
void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(0,
0, getSize().width-1, getSize().height-1);
}
}
[CS411X]
How do I add a couple of panels to a frame?
Dr.
Douglas Lyon (
lyon@snet.net)
Thu,
18 Feb 1999 09:44:10 -0500
import
java.awt.*;
class
ButtonControlPanel
extends
Panel {
Button
b1 = new
Button("BUY");
Button
b2 = new
Button("SELL");
ButtonControlPanel()
{
add(b1);
add(b2);
}
}
class
PricePanel extends
Panel
{
Label
l;
public
void init(String pcs) {
l
= new Label(pcs);
add(l);
setLayout(
new
GridLayout(0,1));
}
PricePanel(String
pcs) {
init(pcs);
update(pcs);
}
public
void update(
String
pcs){
l.setText(pcs);
}
}
public
class PriceArrayFrame
extends
Frame {
PricePanel
pp =
new
PricePanel(
"aapl,38.75,+1.25");
public
void init() {
setLayout(new
GridLayout(0,1,20,30));
add(new
PricePanel(
"aapl,38.75,+1.25"));
add(new
PricePanel(
"aapl,38.75,+1.25"));
add(new
PricePanel(
"aapl,38.75,+1.25"));
add(new
PricePanel(
"aapl,38.75,+1.25"));
add(new
ButtonControlPanel());
pack();
setVisible(true);
}
public
static
void
main(
String
args[]){
PriceArrayFrame
paf
= new
PriceArrayFrame();
paf.init();
}
}
[CS411X]
How do I use movable components in an interface?
Dr.
Douglas Lyon (
lyon@snet.net)
Wed,
17 Feb 1999 07:08:14 -0500
The
following code provides the front-end
for
the network of workstations. The new component,
called
the RectangleComponent, extends the MovableComponent.
As
a result, when the cursor moves over the rectangle,
the
shape of the cursor changes and a click and
drag
of the mouse enables the user to move the component.
More
importantly, the AWT conducts the damage control,
so
that only a small area is repainted. This greatly speeds
the
interactive feel of the program.
-
Doug
import
java.awt.*;
import
java.awt.event.*;
public
class Display extends
ClosableFrame
implements
ComponentListener
{
public
void componentShown(
ComponentEvent
e){}
public
void componentMoved(
ComponentEvent
e){}
public
void componentHidden(
ComponentEvent
e){}
public
void componentResized(
ComponentEvent
e){
pack();
}
public
CpuPanel[] addCpus(int N) {
setLayout(new
GridLayout(2,1));
setBackground(Color.white);
PapPanel
pap =
new
PapPanel(N);
add
(pap);
add
(new BCP(this));
pack();
return
pap.cpuPanels;
}
public
void incrementCpus() {
for
(int i =0; i<cpus.length;i++) {
cpus[i].setSpeed(cpus[i].getSpeed()+1);
cpus[i].setLightOn(true);
}
}
public
void terminateCpus() {
for
(int i =0; i<cpus.length;i++) {
cpus[i].setSpeed(0);
cpus[i].setLightOn(false);
}
}
CpuPanel
cpus[];
public
void init() {
cpus=addCpus(20);
for
(int i =0; i<cpus.length;i++)
cpus[i].setSpeed(i*2+1);
setVisible(true);
addComponentListener(this);
}
public
static void main(String args[]) {
Display
d = new Display();
d.init();
}
}
class
BCP
extends
Panel implements ActionListener {
Button
updateButton = new Button("update");
Button
terminateButton = new Button("terminate");
Display
display;
BCP(Display
_display) {
display
= _display;
setBackground(Color.white);
add(updateButton);
add(terminateButton);
updateButton.addActionListener(this);
terminateButton.addActionListener(this);
}
public
void actionPerformed(ActionEvent e) {
if
(e.getSource()==updateButton) {
display.incrementCpus();
return;
}
if
(e.getSource()==terminateButton) {
display.terminateCpus();
return;
}
}
}
class
CpuControlPanel
extends
Panel {
CpuControlPanel()
{
setLayout(new
GridLayout(0,3));
}
}
class
CpuPanel
extends
Panel implements ItemListener {
private
CpuControlPanel cpucp
=
new CpuControlPanel();
private
Label speedLabel =
new
Label("0");
private
Choice cpuInfo
=
new Choice();
private
RectangleComponent onLight =
new
RectangleComponent(false);
private
Checkbox cb =
new
Checkbox("on",true);
private
static
int
cpuNumber = 0;
private
float speed = 0;
CpuPanel(String
cpuName) {
setBackground(Color.white);
cpuNumber++;
setLayout(new
GridLayout(0,1));
cpucp.add(onLight);
cpucp.add(cb);
cb.addItemListener(this);
cpucp.add(speedLabel);
cpuInfo.add("CPU:"+cpuNumber);
cpuInfo.add(cpuName);
cpuInfo.setBackground(Color.white);
add(cpucp);
add(cpuInfo);
}
public
void setSpeed(float _speed) {
speed
= _speed;
speedLabel.setText
("
"+speed);
}
public
float getSpeed() {
return
speed;
}
public
void setLightOn(boolean on) {
onLight.setState(on);
cb.setState(on);
}
void
checkboxChanged() {
onLight.setState(cb.getState());
//activate
cpu or
//deactivecpu
}
public
void itemStateChanged(ItemEvent e) {
if
(e.getSource() == cb) {
checkboxChanged();
return;
}
}
}
class
PapPanel extends
Panel
{
CpuPanel
cpuPanels[];
PapPanel(
int
numberOfCPUs) {
cpuPanels
=
new
CpuPanel[numberOfCPUs];
setBackground(Color.white);
setLayout(
new
GridLayout(5,0,10,20));
for
(int i=0;
i
< numberOfCPUs; i++) {
cpuPanels[i]=
new
CpuPanel(
"192.107.38."+(i+20));
add(cpuPanels[i]);
}
}
}
class
CircleComponent
extends
MovableComponent {
public
void paint(Graphics g) {
g.drawOval(
getLocation().x,
getLocation().y,
getSize().width,
getSize().height);
}
}
abstract
class MovableComponent
extends
Component
implements
MouseMotionListener {
private
int w=10;
private
int h=5;
private
boolean initialized = init();
private
boolean init() {
addMouseMotionListener(this);
setCursor(
Cursor.getPredefinedCursor(
Cursor.HAND_CURSOR));
return
true;
}
public
void mouseMoved(
MouseEvent
e) {}
public
void mouseDragged(
MouseEvent
e) {
setLocation(
e.getX(),
e.getY());
}
abstract
public void paint(Graphics g);
public
Dimension getPreferredSize() {
return
new Dimension(w,h);
}
}
class
RectangleComponent
extends
MovableComponent
implements
ActionListener {
private
boolean on = true;
public
RectangleComponent(boolean state) {
on
= state;
addActionListener(this);
}
public
void setState(boolean _on) {
on
= _on;
repaint();
}
public
void paint(Graphics g) {
setBackground(Color.white);
Point
pt = getLocation();
Dimension
d = getPreferredSize();
if
(on)
g.fillRect(pt.x,pt.y,d.width,d.height);
else
g.drawRect(pt.x,pt.y,d.width,d.height);
}
public
void actionPerformed(ActionEvent e) {
//do
the action thingy,if needed
//repaint();
}
transient
ActionListener actionListener;
public
synchronized void addActionListener(ActionListener l) {
actionListener
= AWTEventMulticaster.add(actionListener, l);
}
public
synchronized void removeActionListener(ActionListener l) {
actionListener
= AWTEventMulticaster.remove(actionListener, l);
}
class
MouseEventHandler extends MouseAdapter {
public
void mousePressed(
MouseEvent
e) {
if
(actionListener != null)
actionListener.actionPerformed(
new
ActionEvent(this,
ActionEvent.ACTION_PERFORMED,
null));
}
}
}
class
ClosableFrame extends Frame
implements
WindowListener {
//
constructor needed to pass
//
window title to class Frame
public
ClosableFrame() {
//
call java.awt.Frame(String) constructor
super();
setBackground(Color.white);
addWindowListener(this);
}
public
void windowClosing(WindowEvent e) {
dispose();
}
public
void windowClosed(WindowEvent e) {};
public
void windowDeiconified(WindowEvent e) {};
public
void windowIconified(WindowEvent e) {};
public
void windowActivated(WindowEvent e) {};
public
void windowDeactivated(WindowEvent e) {};
public
void windowOpened(WindowEvent e) {};
}
// end class ClosableFrame
[CS411X]
How do I intersect a ray with an ellipse?
Dr.
Douglas Lyon (
lyon@snet.net)
Wed,
17 Feb 1999 06:36:19 -0500
Formulate
the code by subst'ing the
parametric
formula of a ray into that of the
implicit
equation for an ellipse. Then solve for the
roots.
The resulting code follows:
public
Vec2d intersect(Ray2d ray) {
double
a=w/2.0;
double
b=h/2.0;
double
xd=ray.d.v[0];
double
yd=ray.d.v[1];
double
xp=ray.p.v[0];
double
yp=ray.p.v[1];
double
deltax = xp-xc;
double
deltay = yp-yc;
double
b2 = b*b;
double
a2 = a*a;
double
A=b2*xd*xd+a2*yd*yd;
double
B=xp*xd*b2-xc*xd*b2+yp*yd*a2-yc*yd*a2;
double
C=deltax*deltax*b2+deltay*deltay*a2-a2*b2;
double
sq=B*B-A*C;
//
Check if intersects
if
(sq<0) return null;
sq=Math.sqrt(sq);
float
t1=(float)((-B-sq)/A);
float
t2=(float)((-B+sq)/A);
//
check if soln behind the ray
if
(t2<0 && t1<0) return null;
//
if t2 is behind the ray, then t1
if
(t2 < 0) return ray.vecOnLine(t1);
//
if t1 is behind the ray, then t2
if
(t1 < 0) return ray.vecOnLine(t2);
//
select the minimum, cause it is closest.
t1
= Math.min(t1,t2);
return
ray.vecOnLine(t1);
}
[CS411X]
How do I put a gui on my stock quotes?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
16 Feb 1999 10:49:37 -0500
Here
is a simple gui for
the
stock quotes. Note, this updates every 2 seconds,
but
has a 20 minute delay....
-
DL
import
java.util.Vector;
import
java.util.StringTokenizer;
import
java.util.Date;
import
java.io.InputStreamReader;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.net.URL;
import
java.awt.*;
public
class QuoteFrame extends Frame {
Vector
quotes = new Vector();
Label
labels[];
public
void init() {
getQuotes();
setBackground(Color.white);
labels
= new Label[quotes.size()];
for
(int i=0; i < quotes.size(); i++) {
labels[i]
= new Label(
(String)quotes.elementAt(i));
add(labels[i]);
}
setLayout(new
GridLayout(0,1,10,10));
pack();
setVisible(true);
}
public
void updateDisplay() {
getQuotes();
for
(int i=0; i < quotes.size(); i++) {
labels[i].setText(
(String)quotes.elementAt(i));
}
}
public
void paint(Graphics g) {
updateDisplay();
repaint(2000);
}
public
Vector getQuotes() {
Vector
s = new Vector();
s.addElement("aapl");
s.addElement("open");
s.addElement("xlnx");
s.addElement("altr");
s.addElement("mot");
s.addElement("cy");
s.addElement("crus");
s.addElement("mtwkf");
s.addElement("sfa");
s.addElement("adbe");
s.addElement("nn");
s.addElement("msft");
s.addElement("sunw");
return
quotes =
Quote.getUrl(
Quote.makeQuoteURLString(s));
}
public
static void main(String args[]) {
QuoteFrame
qf = new QuoteFrame();
qf.init();
}
}
public
class Quote {
public
static void main(String args[]) {
Vector
s = new Vector();
s.addElement("aapl");
s.addElement("open");
s.addElement("xlnx");
s.addElement("altr");
s.addElement("mot");
s.addElement("cy");
s.addElement("crus");
s.addElement("mtwkf");
s.addElement("sfa");
s.addElement("adbe");
s.addElement("nn");
s.addElement("msft");
s.addElement("sunw");
printVector(
getUrl(
makeQuoteURLString(s)));
}
public
static void printVector(Vector v) {
for
(int i =0; i < v.size();i++) {
System.out.println(v.elementAt(i));
}
}
public
static Vector getUrl(String _URLString) {
Vector
contents = new Vector();
BufferedReader
in = null;
try
{
URL
URLString = new URL(_URLString);
in
= new BufferedReader(new
InputStreamReader(URLString.openStream()));
String
line;
contents.addElement("Copyright
1999 by Doug Lyon
http://www.docjava.com");
contents.addElement("symbol\tprice\tdate\ttime"+
"
(20 min. Delay)\t change\t open\t bid\t ask\t volume");
while(null
!= (line = in.readLine()))
contents.addElement(line);
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
try
{
if
(in != null) in.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
return
contents;
}
public
static String makeQuoteURLString(Vector symbols) {
String
symbolsString = "";
for(int
i = 0; i < symbols.size(); i++) {
String
symbol = (String)symbols.elementAt(i);
symbolsString
+= ((i != 0) ? "," : "") + symbol.toUpperCase();
}
return
"http://quote.yahoo.com/download/javasoft.beans?SYMBOLS="
+
symbolsString
+
"&format=sl";
}
}
[CS411X]
How do I get Stockquotes in Java?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
16 Feb 1999 08:57:18 -0500
Try
this:
import
java.util.Vector;
import
java.util.StringTokenizer;
import
java.util.Date;
import
java.io.InputStreamReader;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.net.URL;
public
class Quote {
public
static void main(String args[]) {
Vector
s = new Vector();
s.addElement("aapl");
s.addElement("open");
s.addElement("xlnx");
s.addElement("altr");
s.addElement("mot");
s.addElement("cy");
s.addElement("crus");
s.addElement("mtwkf");
s.addElement("sfa");
s.addElement("adbe");
s.addElement("nn");
s.addElement("msft");
s.addElement("sunw");
Quote.printQuotesFromYahoo(s);
}
static
void printQuotesFromYahoo(Vector symbols) {
{
String
symbolsString = "";
for(int
i = 0; i < symbols.size(); i++) {
String
symbol = (String)symbols.elementAt(i);
symbolsString
+= ((i != 0) ? "," : "") + symbol.toUpperCase();
}
String
quoteURLString =
"http://quote.yahoo.com/download/javasoft.beans?SYMBOLS="
+
symbolsString
+
"&format=sl";
BufferedReader
in = null;
System.out.println("symbol
price date time change open bid ask
volume");
try
{
URL
quoteURL = new URL(quoteURLString);
in
= new BufferedReader(new InputStreamReader(quoteURL.openStream()));
String
line;
while(null
!= (line = in.readLine())) {
StringTokenizer
t = new StringTokenizer(line, ",\"");
System.out.println(line);
String
symbol = t.nextToken();
double
price = Double.valueOf(t.nextToken()).doubleValue();
t.nextToken();
Date
date = new Date();
t.nextToken();
Date
lastTrade = date;
double
change = Double.valueOf(t.nextToken()).doubleValue();
double
open = Double.valueOf(t.nextToken()).doubleValue();
double
bid = Double.valueOf(t.nextToken()).doubleValue();
double
ask = Double.valueOf(t.nextToken()).doubleValue();
int
volume = Integer.valueOf(t.nextToken()).intValue();
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
try
{
if
(in != null) in.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
}
}
[CS411X]
How do I make a movable component?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
16 Feb 1999 04:59:17 -0500
If
you want
a
movable component, all you should ever have
to
do is implement a MovableComponent class.
This
requires an implementation of the paint method...
and
an invocation of house-keeping in the super class.
Note
how we defined a boolean instance variable, called initialized,
which
allows for after-construction house keeping in the
super-class.
-
DL
class
CircleComponent
extends
MovableComponent {
public
void paint(Graphics g) {
g.drawOval(
getLocation().x,
getLocation().y,
getSize().width,
getSize().height);
}
}
abstract
class MovableComponent
extends
Component
implements
MouseMotionListener {
private
int w=10;
private
int h=5;
private
boolean initialized = init();
//
init does the house keeping during construction
private
boolean init() {
addMouseMotionListener(this);
setCursor(
Cursor.getPredefinedCursor(
Cursor.HAND_CURSOR));
return
true;
}
public
void mouseMoved(
MouseEvent
e) {}
public
void mouseDragged(
MouseEvent
e) {
setLocation(
e.getX(),
e.getY());
}
abstract
public void paint(Graphics g);
public
Dimension getPreferredSize() {
return
new Dimension(w,h);
}
}
[CS411X]
How do I nest layouts in panels?
Dr.
Douglas Lyon (
lyon@snet.net)
Thu,
11 Feb 1999 13:38:33 -0500
The
following example shows
how
to nest layouts in panels. Note that
each
panel has its own layout manager.
Also
note that the pack method is only available
in
the fram (not the panel). Pack is required
because
it resizes the window to its preferred
size.
Frame extends window, but panel does not.
Further
only window has the pack method.
Finally,
the pack method called addNotify,
which
causes all the components in the container
hierarchy
to be created.
import
java.awt.*;
public
class PapPanel extends
Panel
{
CpuPanel
cpuPanels[];
PapPanel(
int
numberOfCPUs) {
cpuPanels
=
new
CpuPanel[numberOfCPUs];
setLayout(
new
GridLayout(4,5));
for
(int i=0;
i
< numberOfCPUs; i++) {
cpuPanels[i]=new
CpuPanel(i);
add(cpuPanels[i]);
}
}
}
public
class Display extends
Frame
{
public
CpuPanel[]
addCpus(int
N) {
setLayout(new
GridLayout(2,1));
PapPanel
pap =
new
PapPanel(N);
add
(pap);
add
(new BCP());
pack();
return
pap.cpuPanels;
}
public
static void main(String args[]) {
System.out.println(
"Hello World!" );
Display
d = new Display();
CpuPanel
cpus[]=d.addCpus(20);
d.setVisible(true);
for
(int i =0; i<cpus.length;i++) {
cpus[i].setSpeed(i*2+1);
}
d.repaint();
try
{
System.in.read();
// prevent console window from
going
away
}
catch (java.io.IOException e) {}
}
}
public
class BCP
extends
Panel {
BCP()
{
setLayout(
new
GridLayout(1,2));
add(new
Button("update"));
add(new
Button("Terminate"));
}
}
public
class CpuPanel
extends
Panel {
Label
speedLabel =
new
Label(" 0");
CpuPanel(int
cpuNumber) {
setLayout(new
GridLayout(2,1));
add(speedLabel);
add(new
Label
("CPU
"+cpuNumber));
}
public
void setSpeed(float speed) {
speedLabel
=
new Label(speed+"");
}
}
[CS411X]
How do I intersect a ray with an ellipses?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
5 Feb 1999 09:01:23 -0500
When
a ray is given by:
f(t)=P
+ t D
where
P = start point
and
D = normalized direction vector
Substitute
into the implicit equation for the
curve
(or surface) and solve for t.
Thus,
if the implicit equation for the standard
ellipse
is written:
(1/a)*(x-xc)**2+
(1/b)*(y-yc)**2=1
Then
the center of the ellipse is at:
(xc,yc)
and the semimajor or semiminor
axes
are sqrt(a) and sqrt(b). If a and b have the same value, then
you
have a circle.
Perform
the substitution and rearrange the terms
into
the form of the quadratic equation. If the
determinant
is < 0, the roots are imaginary and
there
is no intersection.
This
approach may be extended to any quadratic curve
or
surface.
-
DL
[CS411X]
How do I set the location of a component?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
2 Feb 1999 12:19:36 -0500
Hi
All,
In
the last CS510 class, I used the
resize
method to set the location of a component.
I
have just learned that this usage has been deprecated
*SURPRISE!*
To
set the location of a component, without using the
layout
manager, use:
setLocation(int
x, int y);
Using
this technique, you should be able to derive a
custom
component layout that is editable using mouse
interaction.
-
DL
[CS411X]
How do I install Java3D?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
27 Oct 1998 19:19:57 -0400
To
install Java3D on your windows systems...just
follow
these 11 easy steps:
1)
Download the following software:
a)
Java 3D 1.1 Beta 1 API
b)
Java Plug-in 1.1.1
c)
Java Plug-in HTML Converter
d)
JDK 1.2 Beta 4
f)
JRE 1.2 Beta 4
2)
Install JDK 1.2 Beta 4.
3)
Install JRE 1.2 Beta 4 into JDK's JRE Directory.
4)
Install Java 3D 1.1 Beta 1 API into the JRE Directory.
5)
Install Java Plug-in 1.1.1 into the Plug-in directory of your
browser.
Enter
the Advanced Settings and use your JRE 1.2 (\jdk\jre).
6)
Install Java Plug-in HTML Converter.
Choose
the "specific" option when asked.
7)
Edit your environment variables to point to the 3D-classes and
3D-dll's,
e.g.:
CLASSPATH
c:\jdk\jre\lib\ext\j3dutils.jar;c:\jdk\jre\lib\ext\j3dcore.jar;c:\jdk\jre\lib\ex
t\vecmath.jar;e:\jdk\jre\lib\ext\j3daudio.jar;e:\jdk\jre\lib\ext\iiimp.jar;.;
P
ATH
c:\jdk\jre\bin;c:\jdk\bin;
8)
Reboot.
9)
Go ahead and compile HelloUniverse.java.
10)
Use the HTML-Converter on that directory.
11)
Open the HelloUniverse.html inside your browser.
Simple
Yes?
-
DL
[CS411X]
How do I draw Points in 3D in Java?
Dr.
Douglas Lyon (
lyon@snet.net)
Thu,
8 Oct 1998 12:02:46 -0500
Hi
All,
Here
is a nice little program for drawing the points around
a
cynlinder...It zooms you in from infinity...
Give
it a try!
-
DL
import
java.awt.*;
import
java.awt.image.*;
public
class DrawPoints extends
java.applet.Applet
implements
Runnable {
Thread
animationThread = null;
int
xsize,ysize,xcenter,ycenter;
int
delay=10;
int
numberOfPoints=1000;
Graphics
backGC;
Image
backBuffer;
int[]
starX,starY,starZ;
Color[]
grayScale;
public
static void main(String args[]) {
Frame
f = new Frame();
DrawPoints
s = new DrawPoints();
f.add(s);
f.setSize(256,256);
f.show();
s.init();
s.start();
}
public
void init()
{
//Get
screen dimensions
xsize=size().width;
ysize=size().height;
xcenter=xsize/2;
ycenter=ysize/2;
//Init
double-buffering
backBuffer
= createImage(xsize, ysize);
backGC
= backBuffer.getGraphics();
starX=new
int[numberOfPoints];
starY=new
int[numberOfPoints];
starZ=new
int[numberOfPoints];
double
theta = 0;
double
eps = (1.0/numberOfPoints) * 2*Math.PI;
for
(int n=0;n<numberOfPoints;n++) {
starX[n]=(int)
((Math.sin(theta)*xsize*2.0)-xsize/2);
starY[n]=(int)
((Math.cos(theta)*ysize*2.0)-ysize/2);
starZ[n]=(int)
(Math.random()*4095);
theta
= theta + eps;
}
//Create
grayscale tones
grayScale=new
Color[256];
for
(int n=0;n<256;n++)
grayScale[255-n]=new
Color(n,n,n);
}
//This
method is called when the applet becomes visible
public
void start()
{
//Create
a thread and start it
if(animationThread
== null)
{
animationThread
= new Thread(this);
animationThread.start();
}
}
//This
method is called when the applet becomes invisible
public
void stop()
{
//Stop
animation thread
animationThread
= null;
}
public
void run()
{
long
time = System.currentTimeMillis();
while
(animationThread != null)
{
//Make
sure the frame rate is constant by using the
system
clock
try
{
time
+= delay;
Thread.sleep(Math.max(
0,
time - System.currentTimeMillis()));
}
catch
(InterruptedException e){};
//Initiate
a repaint of the screen
repaint();
}
}
public
void paint(Graphics g)
{
//Clear
screen
backGC.setColor(Color.black);
backGC.fillRect(0,0,xsize,ysize);
for
(int n=0;n<numberOfPoints;n++)
{
//Move
stars and clip against viewplane
//The
back clipping plane and the
//
view plane are hard coded
//for
optimizing reasons.
//
Viewplane=512, backplane=4095
starZ[n]-=50;
if
(starZ[n]<512) starZ[n]=4095;
int
z=starZ[n];
//Apply
perspective projection
int
x=(starX[n]<<9)/z+xcenter;
int
y=(starY[n]<<9)/z+ycenter;
//Apply
dept shading
backGC.setColor(grayScale[z>>4]);
//Draw
star
backGC.drawLine(x,y,x,y);
}
//Draw
buffer to screen
g.drawImage(backBuffer,
0, 0, this);
}
public
void update(Graphics g) {
paint(g);
}
}
[CS411X]
how do I build servelets in Java?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
29 Sep 1998 04:37:25 -0500
//
This example is from _Java Examples in a Nutshell_. (
http://www.oreilly.com)
//
Copyright (c) 1997 by David Flanagan
//
This example is provided WITHOUT ANY WARRANTY either expressed or implied.
//
You may study, use, modify, and distribute it for non-commercial purposes.
//
For any commercial use, see
http://www.davidflanagan.com/javaexamples
import
java.io.*;
import
java.net.*;
import
java.util.*;
/**
*
This class is a generic framework for a flexible, multi-threaded server.
*
It listens on any number of specified ports, and, when it receives a
*
connection on a port, passes input and output streams to a specified Service
*
object which provides the actual service. It can limit the number of
*
concurrent connections, and logs activity to a specified stream.
**/
public
class Server {
/**
*
A main() method for running the server as a standalone program.
*
The command-line arguments to the program should be pairs of servicenames
*
and port numbers. For each pair, the program will dynamically load the
*
named Service class, instantiate it, and tell the server to provide that
*
Service on the specified port. The special -control argument should be
*
followed by a password and port, and will start special server control
*
service running on the specified port, protected by the specified
*
password.
**/
public
static void main(String[] args) {
try
{
if
(args.length < 2) // Check number of arguments
throw
new IllegalArgumentException("Must start at least one service");
//
Create a Server object that uses standard out as its log and
//
has a limit of ten concurrent connections at once.
Server
s = new Server(System.out, 10);
//
Parse the argument list
int
i = 0;
while(i
< args.length) {
if
(args[i].equals("-control")) { // Handle the -control argument
i++;
String
password = args[i++];
int
port = Integer.parseInt(args[i++]);
s.addService(new
Control(s, password), port); // add control service
}
else
{
//
Otherwise start a named service on the specified port.
//
Dynamically load and instantiate a class that implements Service.
String
serviceName = args[i++];
Class
serviceClass = Class.forName(serviceName); // dynamic load
Service
service = (Service)serviceClass.newInstance(); // instantiate
int
port = Integer.parseInt(args[i++]);
s.addService(service,
port);
}
}
}
catch
(Exception e) { // Display a message if anything goes wrong
System.err.println("Server:
" + e);
System.err.println("Usage:
java Server [-control <password> <port>] " +
"[<servicename>
<port> ... ]");
System.exit(1);
}
}
//
This is the state for the server
ConnectionManager
connectionManager; // The ConnectionManager object
Hashtable
services; // The current services and their ports
ThreadGroup
threadGroup; // The threadgroup for all our threads
PrintWriter
logStream; // Where we send our logging output to
/**
*
This is the Server() constructor. It must be passed a stream
*
to send log output to (may be null), and the limit on the number of
*
concurrent connections. It creates and starts a ConnectionManager
*
thread which enforces this limit on connections.
**/
public
Server(OutputStream logStream, int maxConnections) {
setLogStream(logStream);
log("Starting
server");
threadGroup
= new ThreadGroup("Server");
connectionManager
= new ConnectionManager(threadGroup, maxConnections);
connectionManager.start();
services
= new Hashtable();
}
/**
*
A public method to set the current logging stream. Pass null
*
to turn logging off
**/
public
void setLogStream(OutputStream out) {
if
(out != null) logStream = new PrintWriter(new OutputStreamWriter(out));
else
logStream = null;
}
/**
Write the specified string to the log */
protected
synchronized void log(String s) {
if
(logStream != null) {
logStream.println("["
+ new Date() + "] " + s);
logStream.flush();
}
}
/**
Write the specified object to the log */
protected
void log(Object o) { log(o.toString()); }
/**
*
This method makes the server start providing a new service.
*
It runs the specified Service object on the specified port.
**/
public
void addService(Service service, int port) throws IOException {
Integer
key = new Integer(port); // the hashtable key
//
Check whether a service is already on that port
if
(services.get(key) != null)
throw
new IllegalArgumentException("Port " + port + " already in use.");
//
Create a Listener object to listen for connections on the port
Listener
listener = new Listener(threadGroup, port, service);
//
Store it in the hashtable
services.put(key,
listener);
//
Log it
log("Starting
service " + service.getClass().getName() +
"
on port " + port);
//
Start the listener running.
listener.start();
}
/**
*
This method makes the server stop providing a service on a port.
*
It does not terminate any pending connections to that service, merely
*
causes the server to stop accepting new connections
**/
public
void removeService(int port) {
Integer
key = new Integer(port); // hashtable key
//
Look up the Listener object for the port in the hashtable of services
final
Listener listener = (Listener) services.get(key);
if
(listener == null) return;
//
Ask the listener to stop
listener.pleaseStop();
//
Remove it from the hashtable
services.remove(key);
//
And log it.
log("Stopping
service " + listener.service.getClass().getName() +
"
on port " + port);
}
/**
*
This nested Thread subclass is a "listener". It listens for connections
*
on a specified port (using a ServerSocket) and when it gets a connection
*
request, it calls a method of the ConnectionManager to accept (or reject)
*
the connection. There is one Listener for each Service being provided
*
by the Server. The Listener passes the Server object to the
*
ConnectionManager, but doesn't do anything with it itself.
*/
public
class Listener extends Thread {
ServerSocket
listen_socket; // The socket we listen for connections on
int
port; // The port we're listening on
Service
service; // The service to provide on that port
boolean
stop = false; // Whether we've been asked to stop
/**
*
The Listener constructor creates a thread for itself in the specified
*
threadgroup. It creates a ServerSocket to listen for connections
*
on the specified port. It arranges for the ServerSocket to be
*
interruptible, so that services can be removed from the server.
**/
public
Listener(ThreadGroup group, int port, Service service)
throws
IOException {
super(group,
"Listener:" + port);
listen_socket
= new ServerSocket(port);
//
give the socket a non-zero timeout so accept() can be interrupted
listen_socket.setSoTimeout(600000);
this.port
= port;
this.service
= service;
}
/**
This is the nice way to get a Listener to stop accepting connections */
public
void pleaseStop() {
this.stop
= true; // set the stop flag
this.interrupt();
// and make the accept() call stop blocking
}
/**
*
A Listener is a Thread, and this is its body.
*
Wait for connection requests, accept them, and pass the socket on
*
to the ConnectionManager object of this server
**/
public
void run() {
while(!stop)
{ // loop until we're asked to stop.
try
{
Socket
client = listen_socket.accept();
connectionManager.addConnection(client,
service);
}
catch
(InterruptedIOException e) {}
catch
(IOException e) {log(e);}
}
}
}
/**
*
This nested class manages client connections for the server.
*
It maintains a list of current connections and enforces the
*
maximum connection limit. It creates a separate thread (one per
*
server) that sits around and wait()s to be notify()'d that a connection
*
has terminated. When this happens, it updates the list of connections.
**/
public
class ConnectionManager extends Thread {
int
maxConnections; // The maximum number of allowed connections
Vector
connections; // The current list of connections
/**
*
Create a ConnectionManager in the specified thread group to enforce
*
the specified maximum connection limit. Make it a daemon thread so
*
the interpreter won't wait around for it to exit.
**/
public
ConnectionManager(ThreadGroup group, int maxConnections) {
super(group,
"ConnectionManager");
this.setDaemon(true);
this.maxConnections
= maxConnections;
connections
= new Vector(maxConnections);
log("Starting
connection manager. Max connections: " + maxConnections);
}
/**
*
This is the method that Listener objects call when they accept a
*
connection from a client. It either creates a Connection object
*
for the connection and adds it to the list of current connections,
*
or, if the limit on connections has been reached, it closes the
*
connection.
**/
synchronized
void addConnection(Socket s, Service service) {
//
If the connection limit has been reached
if
(connections.size() >= maxConnections) {
try
{
PrintWriter
out = new PrintWriter(s.getOutputStream());
//
Then tell the client it is being rejected.
out.println("Connection
refused; " +
"server
has reached maximum number of clients.");
out.flush();
//
And close the connection to the rejected client.
s.close();
//
And log it, of course
log("Connection
refused to " + s.getInetAddress().getHostAddress() +
":"
+ s.getPort() + ": max connections reached.");
}
catch (IOException e) {log(e);}
}
else
{ // Otherwise, if the limit has not been reached
//
Create a Connection thread to handle this connection
Connection
c = new Connection(s, service);
//
Add it to the list of current connections
connections.addElement(c);
//
Log this new connection
log("Connected
to " + s.getInetAddress().getHostAddress() +
":"
+ s.getPort() + " on port " + s.getLocalPort() +
"
for service " + service.getClass().getName());
//
And start the Connection thread running to provide the service
c.start();
}
}
/**
*
A Connection object calls this method just before it exits.
*
This method uses notify() to tell the ConnectionManager thread
*
to wake up and delete the thread that has exited.
**/
public
synchronized void endConnection() { this.notify(); }
/**
Change the current connection limit */
public
synchronized void setMaxConnections(int max) { maxConnections=max; }
/**
*
Output the current list of connections to the specified stream.
*
This method is used by the Control service defined below.
**/
public
synchronized void printConnections(PrintWriter out) {
for(int
i = 0; i < connections.size(); i++) {
Connection
c = (Connection)connections.elementAt(i);
out.println("CONNECTED
TO " +
c.client.getInetAddress().getHostAddress()
+ ":" +
c.client.getPort()
+ " ON PORT " + c.client.getLocalPort()+
"
FOR SERVICE " + c.service.getClass().getName());
}
}
/**
*
The ConnectionManager is a thread, and this is the body of that
*
thread. While the ConnectionManager methods above are called by other
*
threads, this method is run in its own thread. The job of this thread
*
is to keep the list of connections up to date by removing connections
*
that are no longer alive. It uses wait() to block until notify()'d by
*
the endConnection() method.
**/
public
void run() {
while(true)
{ // infinite loop
//
Check through the list of connections, removing dead ones
for(int
i = 0; i < connections.size(); i++) {
Connection
c = (Connection)connections.elementAt(i);
if
(!c.isAlive()) {
connections.removeElementAt(i);
log("Connection
to " + c.client.getInetAddress().getHostAddress() +
":"
+ c.client.getPort() + " closed.");
}
}
//
Now wait to be notify()'d that a connection has exited
//
When we wake up we'll check the list of connections again.
try
{ synchronized(this) { this.wait(); } }
catch(InterruptedException
e) {}
}
}
}
/**
*
This class is a subclass of Thread that handles an individual connection
*
between a client and a Service provided by this server. Because each
*
such connection has a thread of its own, each Service can have multiple
*
connections pending at once. Despite all the other threads in use, this
*
is the key feature that makes this a multi-threaded server implementation.
**/
public
class Connection extends Thread {
Socket
client; // The socket to talk to the client through
Service
service; // The service being provided to that client
/**
*
This constructor just saves some state and calls the superclass
*
constructor to create a thread to handle the connection. Connection
*
objects are created by Listener threads. These threads are part of
*
the server's ThreadGroup, so all Connection threads are part of that
*
group, too.
**/
public
Connection(Socket client, Service service) {
super("Server.Connection:"
+ client.getInetAddress().getHostAddress() +
":"
+ client.getPort());
this.client
= client;
this.service
= service;
}
/**
*
This is the body of each and every Connection thread.
*
All it does is pass the client input and output streams to the
*
serve() method of the specified Service object. That method
*
is responsible for reading from and writing to those streams to
*
provide the actual service. Recall that the Service object has been
*
passed from the Server.addService() method to a Listener object
*
to the ConnectionManager.addConnection() to this Connection object,
*
and is now finally getting used to provide the service.
*
Note that just before this thread exits it calls the
*
ConnectionManager.endConnection() method to wake up the
*
ConnectionManager thread so that it can remove this Connection
*
from its list of active connections.
**/
public
void run() {
try
{
InputStream
in = client.getInputStream();
OutputStream
out = client.getOutputStream();
service.serve(in,
out);
}
catch
(IOException e) {log(e);}
finally
{ connectionManager.endConnection(); }
}
}
/**
*
Here is the Service interface that we have seen so much of.
*
It defines only a single method which is invoked to provide the service.
*
serve() will be passed an input stream and an output stream to the client.
*
It should do whatever it wants with them, and should close them before
*
returning.
*
*
All connections through the same port to this service share a single
*
Service object. Thus, any state local to an individual connection must
*
be stored in local variables within the serve() method. State that should
*
be global to all connections on the same port should be stored in
*
instance variables of the Service class. If the same Service is running
*
on more than one port, there will typically be different Service instances
*
for each port. Data that should be global to all connections on any port
*
should be stored in static variables.
*
*
Note that implementations of this interface must have a no-argument
*
constructor if they are to be dynamically instantiated by the main()
*
method of the Server class.
**/
public
interface Service {
public
void serve(InputStream in, OutputStream out) throws IOException;
}
/**
*
A very simple service. It displays the current time on the server
*
to the client, and closes the connection.
**/
public
static class Time implements Service {
public
void serve(InputStream i, OutputStream o) throws IOException {
PrintWriter
out = new PrintWriter(new OutputStreamWriter(o));
out.println(new
Date());
out.close();
i.close();
}
}
/**
*
This is another example service. It reads lines of input from the
*
client, and sends them back, reversed. It also displays a welcome
*
message and instructions, and closes the connection when the user
*
enters a '.' on a line by itself.
**/
public
static class Reverse implements Service {
public
void serve(InputStream i, OutputStream o) throws IOException {
BufferedReader
in = new BufferedReader(new InputStreamReader(i));
PrintWriter
out =
new
PrintWriter(new BufferedWriter(new OutputStreamWriter(o)));
out.println("Welcome
to the line reversal server.");
out.println("Enter
lines. End with a '.' on a line by itself");
for(;;)
{
out.print(">
");
out.flush();
String
line = in.readLine();
if
((line == null) || line.equals(".")) break;
for(int
j = line.length()-1; j >= 0; j--)
out.print(line.charAt(j));
out.println();
}
out.close();
in.close();
}
}
/**
*
This service is an HTTP mirror, just like the HttpMirror class
*
implemented earlier in this chapter. It echos back the client's
*
HTTP request
**/
public
static class HTTPMirror implements Service {
public
void serve(InputStream i, OutputStream o) throws IOException {
BufferedReader
in = new BufferedReader(new InputStreamReader(i));
PrintWriter
out = new PrintWriter(new OutputStreamWriter(o));
out.println("HTTP/1.0
200 ");
out.println("Content-Type:
text/plain");
out.println();
String
line;
while((line
= in.readLine()) != null) {
if
(line.length() == 0) break;
out.println(line);
}
out.close();
in.close();
}
}
/**
*
This service demonstrates how to maintain state across connections
*
by saving it in instance variables and using synchronized access to
*
those variables. It maintains a count of how many clients have connected
*
and tells each client what number it is
**/
public
static class UniqueID implements Service {
public
int id=0;
public
synchronized int nextId() { return id++; }
public
void serve(InputStream i, OutputStream o) throws IOException {
PrintWriter
out = new PrintWriter(new OutputStreamWriter(o));
out.println("You
are client #: " + nextId());
out.close();
i.close();
}
}
/**
*
This is a non-trivial service. It implements a command-based protocol
*
that gives password-protected runtime control over the operation of the
*
server. See the main() method of the Server class to see how this
*
service is started.
*
*
The recognized commands are:
*
password: give password; authorization is required for most commands
*
add: dynamically add a named service on a specified port
*
remove: dynamically remove the service running on a specified port
*
max: change the current maximum connection limit.
*
status: display current services, connections, and connection limit
*
help: display a help message
*
quit: disconnect
*
*
This service displays a prompt, and sends all of its output to the user
*
in capital letters. Only one client is allowed to connect to this service
*
at a time.
**/
public
static class Control implements Service {
Server
server; // The server we control
String
password; // The password we require
boolean
connected = false; // Whether a client is already connected to us
/**
*
Create a new Control service. It will control the specified Server
*
object, and will require the specified password for authorization
*
Note that this Service does not have a no argument constructor, which
*
means that it cannot be dynamically instantiated and added as the other,
*
generic services above can be.
**/
public
Control(Server server, String password) {
this.server
= server;
this.password
= password;
}
/**
*
This is the serve method that provides the service. It reads a line
*
the client, and uses java.util.StringTokenizer to parse it into
*
commands and arguments. It does various things depending on the
*
command.
**/
public
void serve(InputStream i, OutputStream o) throws IOException {
//
Setup the streams
BufferedReader
in = new BufferedReader(new InputStreamReader(i));
PrintWriter
out = new PrintWriter(new OutputStreamWriter(o));
String
line;
boolean
authorized = false; // Has the user has given the password yet?
int
num;
//
If there is already a client connected to this service, display a
//
message to this client and close the connection. We use a
//
synchronized block to prevent a race condition.
synchronized(this)
{
if
(connected) {
out.println("ONLY
ONE CONTROL CONNECTION ALLOWED AT A TIME.");
out.close();
return;
}
else
connected = true;
}
for(;;)
{ // infinite loop
out.print(">
"); // Display a prompt
out.flush();
// Make it appear right away
line
= in.readLine(); // Get the user's input
if
(line == null) break; // Quit if we get EOF.
try
{
//
Use a StringTokenizer to parse the user's command
StringTokenizer
t = new StringTokenizer(line);
if
(!t.hasMoreTokens()) continue; // if input was blank line
//
Get the first word of the input and convert to lower case
String
command = t.nextToken().toLowerCase();
//
Now compare it to each of the possible commands, doing the
//
appropriate thing for each command
if
(command.equals("password")) { // Password command
String
p = t.nextToken(); // Get the next word of input
if
(p.equals(this.password)) { // Does it equal the password
out.println("OK");
// Say so
authorized
= true; // Grant authorization
}
else
out.println("INVALID PASSWORD"); // Otherwise fail
}
else
if (command.equals("add")) { // Add Service command
//
Check whether password has been given
if
(!authorized) out.println("PASSWORD REQUIRED");
else
{
//
Get the name of the service and try to dynamically load
//
and instantiate it. Exceptions will be handled below
String
serviceName = t.nextToken();
Class
serviceClass = Class.forName(serviceName);
Service
service;
try
{ service = (Service) serviceClass.newInstance(); }
catch
(NoSuchMethodError e) {
throw
new IllegalArgumentException("Service must have a " +
"no-argument
constructor");
}
int
port = Integer.parseInt(t.nextToken());
//
If no exceptions occurred, add the service
server.addService(service,
port);
out.println("SERVICE
ADDED"); // acknowledge
}
}
else
if (command.equals("remove")) { // Remove service command
if
(!authorized) out.println("PASSWORD REQUIRED");
else
{
int
port = Integer.parseInt(t.nextToken()); // get port
server.removeService(port);
// remove the service on it
out.println("SERVICE
REMOVED"); // acknowledge
}
}
else
if (command.equals("max")) { // Set max connection limit
if
(!authorized) out.println("PASSWORD REQUIRED");
else
{
int
max = Integer.parseInt(t.nextToken()); // get limit
server.connectionManager.setMaxConnections(max);
// set limit
out.println("MAX
CONNECTIONS CHANGED"); // acknowledge
}
}
else
if (command.equals("status")) { // Status Display command
if
(!authorized) out.println("PASSWORD REQUIRED");
else
{
//
Display a list of all services currently running
Enumeration
keys = server.services.keys();
while(keys.hasMoreElements())
{
Integer
port = (Integer) keys.nextElement();
Listener
listener = (Listener)server.services.get(port);
out.println("SERVICE
" + listener.service.getClass().getName()+
"
ON PORT " + port);
}
//
Display a list of all current connections
server.connectionManager.printConnections(out);
//
Display the current connection limit
out.println("MAX
CONNECTIONS: " +
server.connectionManager.maxConnections);
}
}
else
if (command.equals("help")) { // Help command
//
Display command syntax. Password not required
out.println("COMMANDS:\n"
+
"\tpassword
<password>\n" +
"\tadd
<service> <port>\n" +
"\tremove
<port>\n" +
"\tmax
<max-connections>\n" +
"\tstatus\n"
+
"\thelp\n"
+
"\tquit");
}
else
if (command.equals("quit")) break; // Quit command. Exit.
else
out.println("UNRECOGNIZED COMMAND"); // Unknown command error
}
catch
(Exception e) {
//
If an exception occurred during the command, print an error
//
message, then output details of the exception.
out.println("EXCEPTION
WHILE PARSING OR EXECUTING COMMAND:");
out.println(e);
}
}
//
Finally, when the loop command loop ends, close the streams
//
and set our connected flag to false so that other clients can
//
now connect.
out.close();
in.close();
connected
= false;
}
}
}
[CS411X]
How do I grab a frame?
Dr.
Douglas Lyon (
lyon@snet.net)
Sun,
27 Sep 1998 07:08:38 -0500
//
Copyright 1998, Prof. D. Lyon
//
import
java.awt.*;
import
quicktime.qd.*;
import
quicktime.*;
import
quicktime.std.StdQTConstants;
import
quicktime.std.sg.*;
import
quicktime.app.image.*;
import
java.io.*;
public
class FrameGrab
implements
StdQTConstants
{
public
static void main (String args[]) {
FrameGrab
fg = new FrameGrab();
fg.snapShot();
System.out.println("click");
}
private
SequenceGrabber sg;
public
static Image pictToImage(Pict inPict) {
ImageData
id = null;
try
{
id.fromPict(inPict);
}
catch (Exception e) {
System.out.println(e);
};
QDRect
r = id.getDisplayBounds();
Image
i = null;
try
{
i
=
Toolkit.getDefaultToolkit().createImage(new
QTImageProducer(
id,
new
Dimension(
r.getWidth(),
r.getHeight())));
}
catch
(Exception e) {
System.out.println(e);
}
return
i;
}
public
void toFile() {
FileDialog
fd = new FileDialog(
new
Frame(),
"Gimme
a pict name",
FileDialog.SAVE);
fd.show();
String
fn= fd.getDirectory()+fd.getFile();
toFile(fn);
}
public
void toFile(String fn) {
File
file =
new
File(fn);
Pict
p = getPict();
try
{
p.writeToFile(file);
}
catch
(Exception e) {
System.out.println(e);
};
}
public
Image getImage() {
return
pictToImage(getPict());
}
public
Pict getPict() {
try
{
sg
= new SequenceGrabber();
}
catch
(Exception e) {
System.out.println(e);
};
int
offScreenDepth=8;
int
grabPictFlags =
seqGrabToMemory
|
seqGrabPreview
|
seqGrabRecord
|
seqGrabPlayDuringRecord
;
QDRect
bounds=new QDRect(256,256);
Pict
p = null;
try
{
p
= Pict.fromSequenceGrabber(
sg,
bounds,
offScreenDepth,
grabPictFlags);
}
catch
(Exception e) {};
return
p;
}
private
void snapShot() {
try{
QTSession.open();
toFile();
}
catch (Exception ee) {
ee.printStackTrace();
QTSession.close();
}
}
}
[CS411X]
How do I play notes in Java?
Dr.
Douglas Lyon (
lyon@snet.net)
Sat,
26 Sep 1998 06:31:51 -0500
>>QTSession.open();
>>NoteAllocator
myAllo = new NoteAllocator();
>>NoteChannel
myChan = new NoteChannel(myAllo, 25);
>>myChan.playNote(62,
127);
>>
>>all
this is great.. but it drops out to time [badly] when i loop it:
>>
>>QTSession.open();
>>NoteAllocator
myAllo = new NoteAllocator();
>>NoteChannel
myChan = new NoteChannel(myAllo, 25);
>>
>>while(true){
>>
myChan.playNote (61, 127);
>>
delay(na, 1500);
>>
myChan.playNote (61, 0);
>>}
>>
>>static
void delay (NoteAllocator na, long ms) {
>>
try { myAllo.task(); Thread.sleep(ms); }
>>
catch (Exception e) { e.printStackTrace(); }
>>}
>
>The
problem here is probably in the latency of threads that seem to plague
>Java
implementations. You can try the Object.wait methods - I've recently
>been
talking about this with Patrick and he thought that they may get a
>more
accurate timing response.
>
>>this
seems to go out of time (is there a better way????)... if not i've had
>>a
rethink..
>>
>>what
if i set up an bite array [or of the like] that has a list of note
>>numbers
that would b played one at time (ie timeStamped) [62, 63, 64, 65,
>>66]..
then pass this list to my channel to play and loop.. (as if it was
>>playing
a file..)
>>
>>..
but the thing i also need to do is change one of the notes in the list
>>(at
a random time) say 65 to 42 that would give us a list of [62, 63, 64,
>>42,
66].
>
>The
QTMusic architecture does exactly this kind of thing and you will get a
>lot
better timing from QT itself than from Java. You could use the
>TunePlayer
itself or create a movie adding music data to the movie and then
>just
playing the movie. There is a pdf document on the qt web site
>(http://www.apple.com/quicktime/developers/)
that is completely devoted to
>the
music architecture.
[CS411X]
How will I earn a grade in Embedded Control?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
25 Sep 1998 08:08:05 -0500
For
those who are
earning
a grade in embedded control;
You
must write up the labs
as
we complete them. This will be the basis for
your
grade in the course. As a result, there
will
be no final or midterm.
Labs
are graded for there English content.
Labs
must be submitted on paper, but should be
in
an electronic format so that they can also
appear
on the web. Web conversion will
occur
only after the labs have been graded and
approved.
I
can assist you with the web conversion, if you submit
the
lab on floppy.
The
lab should be written to give the student
enough
information to perform the task.
That
is:
Like
a cook book!
For
example:
Pancakes
- yields 15 pancakes + PhD
Materials:
1.5
cps flour, 2.5 tsp baking pdr, 2 cps milk
Procedure:
Use
medium to hot heat. Use non-stick spray. Raise
temperature
to leyden frost point (drops dance on pan).
mix
well, place in heated, greased pan, 1/8 cp at a time.
Objective:
Describe
basic physics behind leyden frost point.
Compute
the vapor pressure of mixture.
Measure
the temperature of pan.
Devise
a robtic control mechanism for automating
the
pancake production process. Describe the
sensor
feedback systems needed to detect
doneness
and flip pancakes.
Limit
your self to a robot with two arms.
Vision
is permitted as a sensor.
Topics
for further research:
How
does cold batter cool the surface of
the
hot pan?
Are
pan-cakes better if flipped before they are
cooked
all the way on one side?
Which
of the Navier-Stokes terms may be reduced
from
the mix-flow equations, using destructive modeling?
Are
batters thixotropic?
Can
level set methods be used to compute the pancake
boundary's
growth?
------------------------
I
have written up the below experiment in a first
draft
form. For credit, you must complete
and
flesh out the lab. Plan on writing a total
of
about 3-5 pages.
Experiment
1: The Serial Port
Objectives
After
performing this experiment, you will be able to
Explain
the operation of the serial port
Contruct
a driver for interface to the serial port
Draw
a timing diagram of the data stream to and from the
serial
port.
Explain
the use of the framing and parity bits.
Materials
Needed
Serial
Cable
Computer,
with Java
Modem
Summary
of Theory
The
serial port simplifies the interconnection of
computers
and peripherals by providing a simple
three
wire interface. It also has a more elaborate
interface
which uses hardware handshaking.
The
serial interface support bi-directional data
transmission.
(explain
duplex, full and half, as well as the
the
control lines).
Procedure
1.
For this experiment, a modem is hooked to a computer.
Use
a terminal program to verify that the modem is connected
correctly.
The command:
atdt5551234
Should
cause the modem to dial, with an audible ring.
2.
use the following Java program to drive the serial
port
and make the modem dial out.
3.
Using the following AT modem command set, vary
the
delay between the touch tones.
4.
Alter the program to make the delay between the touch
tones
a parameter which is passed to dialing string.
Report
for experiment 1
Name:_________________
Date:________________
Objectives
Explain
the operation of the rs-232 port.
Construct
a serial port driver and interface your
computer
with a modem.
Draw
a timing diagram for the handshake and data:
DSR
DTR
TX
RX
Results
and Conclusions:
Topics
for further investigation:
Evaluation
and Review Questions
1.
Why doesn't the serial port transmitter overload the
serial
port reciever?
2.
How does the serial port detect the handshake signals
that
come back from the controller?
3.
Is negative or positive-true logic used for the handshaking?
[CS411X]
How do I capture a video sequence?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
25 Sep 1998 08:08:05 -0500
/*
*
quicktime.app: Sample Code for Initial Seeding
*
*
© 1996, 97 Copyright, Apple Computer
*
All rights reserved
*/
//
This gives you a good summary of the
//
classes that are used in this demo
import
java.awt.*;
import
java.awt.event.*;
import
quicktime.qd.*;
import
quicktime.*;
import
quicktime.util.QTUtils;
import
quicktime.app.util.*;
import
quicktime.io.*;
import
quicktime.std.StdQTConstants;
import
quicktime.std.sg.*;
import
quicktime.app.sg.SGDrawer;
import
quicktime.app.util.*;
import
quicktime.std.movies.*;
import
quicktime.app.display.QTCanvas;
public
class SGCapture extends Frame implements WindowListener,
StdQTConstants,
Errors {
static
final int kWidth = 320;
static
final int kHeight = 240;
public
static void main (String args[]) {
try
{
SGCapture
pm = new SGCapture("QT in Java");
pm.show();
pm.toFront();
}
catch (Exception e) {
e.printStackTrace();
QTSession.close();
}
}
void
createMovie () throws QTException {
FileDialog
fd = new FileDialog (this, "Save Movie As...",
FileDialog.SAVE);
fd.show();
if(fd.getFile()
== null)
throw
new QTIOException (userCanceledErr, "");
mFile
= new QTFile(fd.getDirectory() + fd.getFile());
mMovie
= Movie.createMovieFile (mFile,
kMoviePlayer,
createMovieFileDeleteCurFile
|
createMovieFileDontCreateResFile);
}
SGCapture
(String title) {
super
(title);
try
{
QTSession.open();
myQTCanvas
= new
QTCanvas(QTCanvas.kPerformanceResize,
0.5F, 0.5F);
myQTCanvas.setMaximumSize
(new Dimension (640, 480));
setLayout
(new BorderLayout());
add
("Center", myQTCanvas);
addNotify();
Insets
insets = insets();
setBounds
(0, 0, (insets.left + insets.right +
kWidth),
(insets.top + insets.bottom + kHeight));
addWindowListener(this);
}
catch (Exception ee) {
ee.printStackTrace();
QTSession.close();
}
}
private
QTCanvas myQTCanvas;
private
SGSoundChannel mAudio;
private
SGDrawer mDrawable;
private
QTFile mFile;
private
Movie mMovie;
public
void windowClosing (WindowEvent e) {
myQTCanvas.removeClient();
QTSession.close();
dispose();
}
public
void windowIconified (WindowEvent e) {
}
public
void windowDeiconified (WindowEvent e) {
}
public
void windowClosed (WindowEvent e) {
System.exit(0);
}
public
void windowOpened (WindowEvent e) {
try{
createMovie();
SequenceGrabber
mGrabber = new SequenceGrabber();
SGVideoChannel
mVideo = new SGVideoChannel(mGrabber);
mVideo.settingsDialog
();
mVideo.setBounds
(new QDRect(kWidth, kHeight));
mVideo.setUsage
(seqGrabPreview | seqGrabRecord |
seqGrabPlayDuringRecord);
// seqGrabRecord
mAudio
= new SGSoundChannel(mGrabber);
mAudio.setUsage
(seqGrabPreview | seqGrabRecord |
seqGrabPlayDuringRecord);
// seqGrabRecord
mAudio.setVolume
(2);
mDrawable
= new SGDrawer(mVideo);
myQTCanvas.setClient(mDrawable,true);
mGrabber.setDataOutput
(mFile, seqGrabPreview |
seqGrabRecord
| seqGrabPlayDuringRecord);
mGrabber.prepare(true,true);
mGrabber.startPreview();
}
catch (Exception ee) {
ee.printStackTrace();
QTSession.close();
}
}
public
void windowActivated (WindowEvent e) {}
public
void windowDeactivated (WindowEvent e) {}
}
[CS411X]
How do I set the flags to grab a frame?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
25 Sep 1998 08:08:05 -0500
That
seems to
depend
on the application.
int
flags =
seqGrabPreview
|
seqGrabRecord
|
seqGrabPlayDuringRecord;
[CS411X]
How do I convert from pict to image?
Dr.
Douglas Lyon (
lyon@snet.net)
Thu,
24 Sep 1998 05:35:22 -0500
Hi
All,
Once
you have an instance of a Pict class,
is
there a conversion process that will
yield
an instance of a Java Image class?
Image
pictToImage(Pict inPict) {
ImageData
data = ImageData.fromPict(inPict);
QDRect
r = data.getDisplayBounds();
return
Toolkit.getDefaultToolkit().createImage(new
QTImageProducer(data,
new Dimension(r.getWidth(), r.getHeight())));
}
[CS411X]
How do I get a printed copy of QT-Components?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
22 Sep 1998 06:18:54 -0500
http://developer.apple.com/techpubs/mac/QTComponents/QTComponents-2.html
Has
the PDF link...
-
DL
[CS411X]
how do I get QT4Java?
Dr.
Douglas Lyon (
lyon@snet.net)
Tue,
22 Sep 1998 06:16:25 -0500
There
is a new build available on the server:
http://qtj.apple.com/biscotti
username:
kaleida
password:
newton
[CS411X]
How do I learn about digitizing video?
Dr.
Douglas Lyon (
lyon@snet.net)
Mon,
21 Sep 1998 11:01:35 -0500
http://developer.apple.com/techpubs/mac/QTComponents/QTComponents-377.html#HEADI
NG377-0
The
above url will take you to the QT Components
documentation
on digitizing video. This will work on
any
platform that support quicktime.
-
DL
[CS411X]
How do I install the COMM API on NT?
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
18 Sep 1998 07:46:01 -0500
copy
win32com.ddl
into
the
c:\winnt\system
Drag
the jar file to the CW project window.
-
DL
[CS411X]
How do I drive a serial line-based controller? Part2
Dr.
Douglas Lyon (
lyon@snet.net)
Fri,
18 Sep 1998 07:44:28 -0500
In
my last e-mail on this
subject...I
realized that:
String
s = "M,0,0,0,0,0,0,7,0,0";
could
be:
String
s = "M,0,0,0,0,0,0,7,0,0\r\f";
byte
b[] = s.getBytes();
Should
be enough!
Check
the value of the last two bytes by writing
them
as int values to the console...is it 13 and 10?
-
DL
>To
formulate a string+ control
>characters
to an embedded controller, you need to formulate
>to
different byte arrays and concatenate them.
>
>
byte [] st={'M',0,0,0,0,0,0,7,0,0,13,10}; // have
>
>Should
be:
>
>String
s = "M,0,0,0,0,0,0,7,0,0";
>byte
b[] = s.getBytes();
>byte
eb[] = {13,10};
>byte
turnBytes[] = new byte[b.length+eb.length];
>int
i=0;
>for
(; i < b.length; i++) {
>
turnBytes [i]=b[i];
>}
>turnBytes[i]=eb[0];
>turnBytes[i+1]=eb[1];
>
>now
write out the turnBytes....
>
>Got
it?
>
>
- DL
>
>
>>Hi!
>>
>>Here
is my code.
>>If
you can solve the problem, send me a email.
>>
>>-Hak
Kywn Roh
>>
>>//
Hak Kywn Roh (0367641)
>>//
CPE388X
>>//
Assignment #1
>>
>>import
java.io.*;
>>import
java.util.*;
>>import
javax.comm.*;
>>
>>public
class TurnTable
>>{
>>
static Enumeration portList;
>>
static CommPortIdentifier portId;
>>
static SerialPort serialPort;
>>
static OutputStream outputStream;
>>
>>
public static void main(String[] args)
>>
{
>>
TurnTable tt=new TurnTable();
>>
System.out.println("getPortIdentifiers...");
>>
portList=CommPortIdentifier.getPortIdentifiers();
>>
System.out.println("getPortIdentifiers... done!");
>>
>>
while (portList.hasMoreElements())
>>
{
>>
portId=(CommPortIdentifier)portList.nextElement();
>>
if
>>(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
>>
{
>>
>>
if (portId.getName().equals("COM3"))
>>
{
>>
>>
System.out.println("portId="+portId.getName());
>>
try
>>
{
>>
>>
serialPort=(SerialPort)portId.open("SimpleWriteApp", 2000);
>>
System.out.println("Port
>>Open");
>>
}
>>
catch (PortInUseException e)
>>
{
>>
>>
System.out.println(e.currentOwner+" owned this port");
>>
System.out.println("Will
>>try
to close");
>>
serialPort.close();
>>
}
>>
try
>>
{
>>
>>
outputStream=serialPort.getOutputStream();
>>
}
>>
catch (IOException e)
>>
{
>>
System.out.println("Could
>>not
get output Stream:"+e);
>>
}
>>
try
>>
{
>>
>>
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,
>>SerialPort.STOPBITS_2,
SerialPort.PARITY_NONE);
>>
}
>>
catch
>>(UnsupportedCommOperationException
e)
>>
{
>>
System.out.println("Set
>>Serial
Port Params :"+e);
>>
}
>>
try
>>
{
>>
byte [] mn={27, 13, 27, 13, 27, 13, 0};
>>
outputStream.write(mn);
>>
System.out.println("Send
>>magic
number..");
>>
}
>>
catch (IOException e)
>>
{
>>
System.out.println(e);
>>
}
>>
>>
sleepSec(10);
>>
>>
try
>>
{
>>
byte [] st={'M',0,0,0,0,0,0,7,0,0,13,10}; // have
>>to
change this line...
>>
outputStream.write(st);
>>
System.out.println("Move
>>step.");
>>
}
>>
catch (IOException e)
>>
{
>>
System.out.println(e);
>>
}
>>
>>
//tt.step(1);
>>
//sleepSec(2);
>>
//tt.step(2);
>>
//sleepSec(2);
>>
//tt.step(3);
>>
//sleepSec(2);
>>
>>
serialPort.close();
>>
System.out.println("port closed");
>>
>>
try {
>>
System.in.read();
>>
} catch (java.io.IOException e) {}
>>
}
>>
}
>>
}
>>
}
>>
>>
public void step(int n)
>>
{
>>
System.out.println("Move "+n+" steps");
>>
byte [] st={'M',0,0,0,0,0,0,7,0,0,13,10};
>>
for (int i=0;i<n;i++)
>>
try
>>
{
>>
outputStream.write(st);
>>
}
>>
catch (IOException e)
>>
{
>>
System.out.println(e);
>>
}
>>
}
>>
>>
public static void sleepSec(int sec)
>>
{
>>
try
>>
{
>>
Thread.sleep(sec*1000);
>>
}
>>
catch (InterruptedException e) {}
>>
}
>>}
[CS411X]
How do I run quick-time for Java, under windows?
Dr.
Douglas Lyon (
lyon@snet.net)
Wed,
16 Sep 1998 07:50:24 -0500
When
running quick time for java under windows,
use:
c:\jdk1.2beta4\lib\tools.jar;c:\jdk1.2beta4\qt\lib\qtjava.zip;c:\oldjava
\java\lib\classes.zip
have
the QTJavaNative.DLL file in the same directory as
>
the QTJava.zip file. Also check that you have a classes.zip archive in the
>
your JDK \lib directory. JDK 1.2b4 no longer includes classes.zip (they
>
have broken it into several jar files)
[CS411X]
how do I time image processing?
Dr.
Douglas Lyon (
lyon@snet.net)
Thu,
7 May 1998 09:40:44 -0400
To
time image processing tasks,
we
can use the timer class.
To
time the draw task, is a rather different
issue.
One way is to create a memory image,
then
get the graphics context from the image,
finally,
draw to the image. When all the
drawing
is done, display the image.
This
requires that a new image be made each
time.
This is really a waste!
What
is needed is a way to clear the graphics
context
before new invocations of paint.
....paint(Graphics
g) {
g
= g.create(0,0,g.getSize().width, g.getSize().height);
//
now time the paint method...you have erased the old graphics context...
//
does this work? I have not tried it.
//
This is a waste too, because a new graphics context is
//
created each time......Perhaps we should time
//
this. - DL
}
>----------
>X-Sun-Data-Type:
text
>X-Sun-Data-Description:
text
>X-Sun-Data-Name:
text
>X-Sun-Charset:
us-ascii
>X-Sun-Content-Lines:
24
>
>
>Dear
Professor Lyon:
>
>Here
is a small test program that tests Timer.java class.
>I
modified the Timer class before, cause I thought the
>problem
is in the class. Even if I implement the test
>class
for the "old" Timer.class that you sent, I think
>the
results would be the same.
>
>You
were absolutely right, that it is awt deep problem.
>That
concludes the important observation that we cannot
>use
System.currentTimeMillis() when we do image processing.
>What
would be the good solution ?
>
>Thank
you very much.
>
>
>
>Sincerely
yours,
>
>
>Kirill
Golubev
>
>
>----------
>X-Sun-Data-Type:
default
>X-Sun-Data-Description:
default
>X-Sun-Data-Name:
Timer.java
>X-Sun-Charset:
us-ascii
>X-Sun-Content-Lines:
26
>
>
>
>public
class Timer {
>
>
// private long startTime=0;
>
// private long endTime=0;
>
>
public long start() {
>
long startTime = 0;
>
startTime = System.currentTimeMillis();
>
>
return startTime;
>
}
>
>
public void print(String message, long startTm) {
>
>
long endTime = 0;
>
>
endTime = System.currentTimeMillis();
>
System.out.println(
>
message
>
+" "
>
+ (endTime - startTm)/1000.0 + " seconds");
>
}
>
>}
>----------
>X-Sun-Data-Type:
default
>X-Sun-Data-Description:
default
>X-Sun-Data-Name:
TimerTest.java
>X-Sun-Charset:
us-ascii
>X-Sun-Content-Lines:
32
>
>
>import
java.awt.*;
>
>public
class TimerTest {
>
>
Timer t = new Timer();
>
>
TimerTest () {
>
>
int Sum = 0;
>
long startTm = t.start();
>
>
for (int i=0; i<100000; i++)
>
{
>
Sum += random(255);
>
}
>
>
t.print(("Test Timer without paint() took "), startTm);
>
}
>
>
public int random(int r) {
>
return (int) (Math.floor(Math.random()*r));
>
}
>
>
public static void main(String args[]) {
>
for(int i=0; i<10; i++)
>
{
>
TimerTest tt = new TimerTest();
>
System.out.println("");
>
}
>
}
>}
>----------
>X-Sun-Data-Type:
default
>X-Sun-Data-Description:
default
>X-Sun-Data-Name:
TimerTest.class
>X-Sun-Encoding-Info:
uuencode
>X-Sun-Content-Lines:
23
>
>
>Attachment
converted: RAM Disk:TimerTest.class (????/----) (00000015)
Go
to
vinny.bridgeport.edu
LWGate
Home Page.