The Java classes (programs) that were used to count ballots for the August 1999 SHARE meeting election will be used as a examples of SWING (GUI) and 2D coding. The example classes include Java objects the author has developed over the past four three years which serve as working examples of overloading/polymorphism, encapsulation, and inheritance.
This technical session is intended for the Java coder, and centers on working Java code. These are not just sample Java classes, but working classes that the author has found useful in developing Java applications.
The author has been writing programs since 1965 in Fortran, COBOL,
PL/1, Algol, Pascal, C, C++, and various assembly languages. He
has been exploring Java since 1996.
The University of Texas at Austin | 1965-1966 |
Texas Education Agency | 1966-2000 |
Houston Ind. School District | 1975-1981 |
Conroe Ind. School District | 1980-1993 |
United States Navy | 1966-1994 |
Capitol Appraisal Group, Inc. | 1981-2000 |
"Java in 21 Days " by Laura Lemay (SAMS)
"Java in a Nutshell" by David Flanagan (O'Reilly)
"Java SWING " by Robert Eckstein, Marc Loy & Dave Wood (O'Reilly)
"Java 2D Graphics" by Jonathan Knudsen (O'Reilly)
JsrVoteJar.bat 876 Sat Jul 08 12:18:24 CDT 2000 1: jar cmf JsrVote.mnf JsrVote.jar -C \jsr\java\bin JsrVote.class 2: jar uf JsrVote.jar -C \jsr\java\bin JsrVote$1.class 3: jar uf JsrVote.jar -C \jsr\java\bin JsrVote$1$VoteActionListener.class 4: jar uf JsrVote.jar -C \jsr\java\bin JsrVote$1$VoteItemListener.class 5: jar uf JsrVote.jar -C \jsr\java\bin JsrVote$1$VoteMenuListener.class 6: jar uf JsrVote.jar -C \jsr\java\bin JsrVote$1$VoteWindowExit.class 7: jar uf JsrVote.jar -C \jsr\java\bin JsrUtil.class 8: jar uf JsrVote.jar -C \jsr\java\bin JsrSysout.class 9: jar uf JsrVote.jar -C \jsr\java\bin JsrPrint1.class 10: jar uf JsrVote.jar -C \jsr\java\bin JsrLineIn.class 11: jar uf JsrVote.jar -C \jsr\java\bin JsrLineOut.class 12: jar uf JsrVote.jar -C \jsr\java\bin JsrLinePlot.class 13: jar uf JsrVote.jar -C \jsr\java\bin JsrLinePlot$WindowExit.class 14: jar uf JsrVote.jar -C \jsr\java\bin JsrSortString.class 15: jar tf JsrVote.jar JsrVote.mnf 23 Tue Aug 10 22:07:30 CDT 1999 1: Main-Class: JsrVote JsrRep95.bat 28 Mon Jul 10 10:18:38 CDT 2000 1: write.exe share95r.txt JsrVote95.bat 226 Mon Jul 10 10:15:58 CDT 2000 1: rem "set jdkdir=c:\jdk1.2.2" <-- set as appropriate 2: rem either in this bat file, of the system's autoexec.bat file. 3: rem -- the following line actually runs the program. 4: %jdkdir%\bin\java -jar JsrVote.jar share95 5: pause
JsrVote.txt 5620 Mon Jul 10 10:23:10 CDT 2000 1: JsrVote.java--documentation as of July 10, 2000. 2: 3: Assumptions: the following conditions are assumed to exist, JsrVote has 4: limited error checking, it just assumes these states. The program has 5: one parameter (refered to as p1). Input files are "&p1.i.txt" (for example: 6: if &p1 = "share95", then init file is "share95i.txt", and vote file 7: is "share95v.txt". The vote "backup" file will be "share95v.$$$". 8: These files are included as guides for configuration. 9: 10: 1) "&p1.i.txt" exists and is well formed (see share95i.txt for example). 11: In particular # races, and # candidates is critical!!!!! 12: 13: 2) Race title lines are in format "## title" (## is max votes this race). 14: 15: 3) Candidate lines are in format "(k) Name" (k is shortcut key). 16: 17: 4) "&p1.v.txt" is assumed to always exist. 18: first line is assumed to be titles (for Excel). 19: first action (ALWAYS) is to rename "&p1.v.txt" to "&p1.v.$$$" 20: then program reads "&p1.v.$$$", copying to "&p1.v.txt", 21: building vote count (batch and total) arrays. 22: 23: 5) after initial run, contents of "&p1.i.txt" must NOT be changed, except: 24: title line, maximum batches (used for array size calculation), and 25: batch size may be changed. 26: 27: 6) each ballot voted is immediately written to "&p1.v.txt", so recovery 28: is always to last ballot voted. Ballot # is part of data. 29: Recovery can be to any point by simply deleting the unwanted ballots 30: from the "&p1.v.txt" file. You could recover to the beginning point 31: of the last run by deleting the "&p1.v.txt" file and renaming the 32: "&p1.v.$$$" (backup) file to "&p1.v.txt". 33: 34: You can get the JRE from http://java.sun.com/products/jdk/1.2/jre/index.html 35: 36: It's about a 6 megabyte download. After you download it, you run it. The 37: default directory is probably jre1_2_2. 38: 39: Two files are attached. JsrVote.jar is the "java library" file (like a 40: dll). It should have all the classes necessary to run. 41: 42: JsrVote.zip contains the other files to run. You should unzip it into the 43: same directory with the JAR. Then read the JsrVote.txt (documentation) file. 44: 45: JsrVote.txt documents the required files. Of course the best "documentaion" 46: is the sample ...i.txt and ...v.txt files. 47: 48: JsrVoteJar.bat serves only to document the classes that are part of the jar. 49: 50: JsrVote95.bat is a bat file to exec the program using the share95i.txt and 51: share95v.txt files. The only files required to run are the JsrVote95.bat, 52: share95i.txt and share95v.txt files. For the real election, the share95v.txt 53: file should have only one line (the candidate names). 54: 55: You will probably have to set %jdkdir% to jre1_2_2 (the directory 56: where jre install puts java.exe). 57: 58: You may have to change the =print lines in share95i.txt. If you use a 59: network printer replace the LPT1 with the network name 60: "\\printserver\printlpt1" or whatever. If yours is a laserjet change to 61: "ascii" to "hplj", for a desk jet change to "hpdj". Otherwise try "ascii". 62: I have only built in support for printers I use. Most laser jet printers 63: honor the HP command set. 64: 65: If you use a hp laser jet you can change the lines per page from 60 to 72. 66: 67: The ballots per batch number can be changed thruout the day (set to a small 68: number for more batches, thus a more discrete plot). 69: 70: However the # races and candidate information MUST remain fixed. 71: 72: The batch size now is only used for reporting purposes. 73: 74: For example you could change the batch size to 25 to spread the "plot" program out. 75: JsrVote now supports multiple races, and has a GUI (Graphics 2D) plot, as well 76: as old fashioned plot logic that can be printed on a standard line printer 77: (shades of COBOL and MVS!) that looks just fine. 78: 79: The sharei95v.txt file is the cumulative vote file. The first line is the 80: only line required to run. The sample version has been "populated" with votes 81: from a different (non SHARE) election. 82: 83: You might try to run the reports first. If you don't want to print, or don't have a 84: printer supported by my print logic, then you can just run the report 85: without printing, then open the share95r.txt file with WordPad and print 86: from there (I find Lucida Console at 8 points prints great). Each time you 87: run a report, the share95r.txt file gets replaced. You might want to look 88: at the share95r.txt file before you load the program (exec JsrRep95.txt). 89: It is a plot of the sample share95v.txt file. 90: 91: The three reports are accessible from the pull down "Report" menu, and Print 92: On/Off is a checkbox there as well, with a default of no print. 93: 94: All voting can be done with the mouse, or by just typing the # in (#). The 95: program assumes that the candidate lines are in format (#) Candidate name. 96: The # can be any character, and it could be changed during a run. 97: Only the things that affect the array size that can't be changed. 98: Even the candidate names could be changed as well. However, a change 99: to the number of candidates would invalidate the current vote file. 100: For example: the current "sample" vote file was taken from an election that 101: had 10 candidates, and only one race. Convienently the next share election 102: also had ten candidates. All I had to do was modify the share95i.txt file 103: to add the race lines (and change line one of the share95v.txt file), and 104: I had my sample vote data that indicates real voting patterns. 105: 106: Good Luck. If you can make it work then I know I have my jar file set up 107: completely. 108: 109: Thanks for testing it. I hope you like the new interface. share95i.txt 876 Sat Jul 08 13:18:28 CDT 2000 1: =comment may be any # of optional "=" lines. 2: = column 1 = "=", column 2-10 = parameter name, col 11...= value. 3: = ... below is printer name or network path name. 4: =printNAM LPT1 5: = ... valid printTYP are "hplj"=laser jet, "hpdj"=desk jet. 6: = ... only ascii printer tested is Canon BJ-200E 7: =printTYP hl1040 8: =printLPP 060 lines per page (columns 11-13). 9: SHARE 95 Board Election, July 26, 2000 10: 010 maximum # of batches (for memory allocation) 11: 50 batch size (used for reporting only)...first 3 lines may be changed 12: 04 # races ...these #s can NOT be changed!!! 13: 10 # candidates, all races 14: 01 Secretary 15: (1) Michael Stack 16: (2) Martin Timmerman 17: 01 Treausrer 18: (3) Kathy Mayberry 19: (4) Harold Pritchett 20: 02 Director 21: (5) Avi Meshar 22: (6) Linnea Nichols 23: (7) Robert E. Parkes 24: (8) Robert Rosen 25: (9) Pamela J. Taylor 26: (0) Jeffrey Wilk share95r.txt 4675 Sun Jul 09 22:52:32 CDT 2000 1: 1 JsrVote SHARE 95 Board Election, July 26, 2000 2: 2000-07-09@22:52 Plot Votes 3: 0 # Ballots Cast: 289 4: 289+ 5: | 6: | 7: | 8: | 9: | 10: | 11: | 12: | 13: | 14: | 15: | 16: | 17: 216+ 18: | 19: | 20: | 21: | 9 22: | 23: | 4 24: | 5 25: | * 26: | 27: | 5 2 28: | 1 29: 144+ 2 30: | 9 1 31: | 7 32: | 33: | 4 8 34: | * 3 35: | 2 7 36: | 0 37: | * * 38: | * 7 39: | 2 3 0 6 40: | 8 41: | 0 42: 72+ 9 7 6 43: | 5 3 6 44: | * * 45: | 46: | * 6 47: | * 48: |9 6 49: |* 50: |* 51: |0 52: | 53: | 54: 0+---------+---------+---------+---------+---------+---------+---------+---------+ 55: Batches-> share95v.txt 7993 Sun Jul 09 22:54:06 CDT 2000 1: (1) Michael Stack,(2) Martin Timmerman,(3) Kathy Mayberry,(4) Harold Pritchett,(5) Avi Meshar,(6) Linnea Nichols,(7) Robert E. Parkes,(8) Robert Rosen,(9) Pamela J. Taylor,(0) Jeffrey Wilk 2: 0,1,1,1,1,0,0,1,0,0,00001 3: 0,1,1,1,1,1,0,0,0,0,00002 4: 0,0,1,1,1,1,0,0,0,0,00003 5: 0,1,1,1,1,1,0,0,0,0,00004 6: 0,1,0,1,1,0,0,0,0,0,00005 7: 1,1,0,1,1,0,1,0,0,0,00006 8: 1,1,0,1,1,0,0,0,1,0,00007 ... 289: 1,0,0,1,0,0,0,1,1,0,00288 290: 1,0,1,0,1,1,0,0,0,0,00289
JsrLineIn.java 4779 Sun Jun 25 14:01:18 CDT 2000 1: /****************************************************************************** 2: // JsrLineIn.java: 3: * to simplify input of *.txt type files. 4: * Sample Use: 5: * JsrLineIn file1 = new JsrLineIn(); 6: * String[] strfile1[2]; 7: * strfile1[0] = "C:\reqlook.dxx" 8: * while (0 <= file1.read(strfile1[])) 9: { process records from strfile1[1]; 10: * } 11: *------------------------------------------------------------ 12: *2000-06-25 add following methods to make more "object" like. 13: * illustrated by "sample" use. 14: * JsrLineIn file1 = new JsrLineIn(); 15: * String file1Name = "input.txt"; 16: * String file1Line; 17: * file1.setName(file1Name); // open new file (close old if one is open). 18: * // this is a noOP if file1Name matches open file. 19: * while (0 <== file1.getNext() // reads next record 20: * { // returns rec# or -rec# for EOF 21: file1Line = file1.getLine(); // process records here 22: * } 23: * also: int getCount(); returns current record counter 24: * example: (at EOF rec# is negative) 25: * int recordsRead = - file1.getCount(); 26: */ 27: 28: import java.io.*; 29: 30: public class JsrLineIn 31: { 32: static final String COPYRIGHT = 33: "Copyright 1998-2000, JSR Systems. See: www.Jsrsys.com/copyright."; 34: 35: int recNum = 0; // 0 if no open files (see eofNum)! 36: int eofNum = 0; // - recNum of last file closed! 37: String fileLine = ""; // last Line (record) read. 38: String fileName = ""; // name of last open file. 39: 40: //1.0 DataInputStream inFileStream; 41: //1.0 DataInput inFile; 42: BufferedReader inFile; 43: 44: JsrSysout sysout = new JsrSysout(); 45: JsrUtil u = new JsrUtil(); 46: public JsrLineIn() // null constructor 47: { 48: } 49: 50: int open(String parmName) 51: { 52: if (recNum != 0) 53: { 54: close(); 55: } 56: sysout.display("Open Input: " + parmName); 57: // open code here 58: fileName = parmName; 59: recNum = 0; 60: 61: //1.0 try {inFileStream = 62: //1.0 new DataInputStream(new FileInputStream ( fileName)); 63: //1.0 inFile = inFileStream; 64: try {inFile = new BufferedReader(new InputStreamReader 65: (new FileInputStream ( fileName)),1000000); 66: } catch (FileNotFoundException eFNF) 67: {System.out.println("FileNotFound: " + fileName); 68: recNum=-1; 69: } 70: return recNum; 71: } 72: int close() 73: { 74: sysout.display("Close Input: " + u.padLeft(recNum,10) 75: + " Records: "+ fileName 76: +" "); 77: if (recNum >= 0) 78: { 79: //1.0 try {inFileStream.close(); // free up resource 80: try {inFile.close(); // free up resource 81: }catch ( IOException eIO ) 82: {System.out.println("I/OError! " + fileName); } 83: } 84: eofNum = - recNum; 85: recNum = 0; 86: fileName = ""; 87: //sysout.display("closeReturn: "+eofNum+": "+recNum); 88: return eofNum; 89: } 90: 91: // the following "object" methods were added 2000-06-35 92: 93: int getCount() 94: { 95: if (recNum > 0) return recNum; // file currently open 96: else return eofNum; // eof (- count) last file Read 97: } 98: 99: void setName(String parmName) 100: { 101: if (!parmName.equals(fileName)) 102: { 103: open(parmName); 104: } 105: } 106: 107: int getNext() 108: { 109: if (fileName.equals("")) 110: { 111: sysout.display("JsrLineIn--must use setName([name of File])!!!"); 112: sysout.display("JsrLineIn--before reading w/ getNext()!!!!!!!!"); 113: return -1; 114: } 115: if (recNum >= 0) 116: { 117: try {fileLine = inFile.readLine(); 118: } 119: catch ( IOException eIO ) 120: {System.out.println("I/OError! " + fileName); } 121: if (fileLine == null) 122: return close(); 123: else 124: recNum++; 125: } 126: // sysout.display ("recNum="+recNum+ "Rec="+ fileLine); 127: return recNum; 128: } 129: 130: String getLine() 131: { 132: return fileLine; 133: } 134: 135: // the following method is kept for backward compatability! 136: int read(String nameRecord[]) 137: { 138: // sysout.display("Read: " + nameRecord[0]); 139: if (!nameRecord[0].equals(fileName)) 140: { 141: open(nameRecord[0]); 142: } 143: if (recNum >= 0) 144: { 145: try {nameRecord[1] = inFile.readLine(); 146: } 147: catch ( IOException eIO ) 148: {System.out.println("I/OError! " + fileName); } 149: if (nameRecord[1] == null) 150: return close(); 151: else 152: recNum++; 153: } 154: // sysout.display ("recNum="+recNum+ "Rec="+ nameRecord[1]); 155: return recNum; 156: } 157: } JsrLineOut.java 4210 Tue Jul 11 17:21:50 CDT 2000 1: /****************************************************************************** 2: // JsrLineOut.java: 3: * Sample Use: 4: * JsrLineOut file1 = new JsrLineOut(); 5: * String[] strfile1[2]; 6: * strfile1[0] = "C:\reqlook.dxx" 7: * file1.Write(strfile1[])) 8: * 9: *2000-06-25 add following methods to make more "object" like. 10: * illustrated by "sample" use. 11: * JsrLineOut file1 = new JsrLineOut(); 12: * String file1Name = "output.txt"; 13: * String file1Line; 14: * ... 15: * file1.write(file1Name, file1Line); 16: * // if file1Name is differnet from last method call 17: * // open new file (close old if one is open). 18: * 19: *2000-07-11 add the following to make even more object like. 20: * file1.setName(file1Name); // call once for each file 21: * file1.setLine(file1Line); // call for each line to be written 22: * file1.setFlush(true/false); // if true cause flush() after each line written. 23: */ 24: 25: import java.io.*; 26: 27: public class JsrLineOut 28: { 29: static final String COPYRIGHT = 30: "Copyright 1998-2000, JSR Systems. See: www.Jsrsys.com/copyright."; 31: 32: boolean flushOn = false; 33: int recNum = 0; 34: String fileName = ""; 35: //1.0 DataOutputStream outFileStream; 36: //1.0 DataOutput outFile; 37: BufferedWriter outFile; 38: JsrSysout sysout; 39: boolean displayOn; 40: JsrUtil u = new JsrUtil(); 41: 42: public JsrLineOut() // null constructor 43: { 44: sysout = new JsrSysout(); 45: displayOn = true; 46: } 47: public JsrLineOut(String noLog) // constructor to not log 48: { displayOn = false; // used by JsrSysout itself 49: } // to avoid recursive calls 50: 51: int open(String parmName) 52: { 53: if (recNum != 0) 54: { 55: close(); 56: } 57: if (displayOn) sysout.display("Open Output: " + parmName); 58: // open code here 59: fileName = parmName; 60: recNum = 0; 61: //1.0try {outFileStream = 62: //1.0 new DataOutputStream(new FileOutputStream ( fileName)); 63: //1.0 outFile = outFileStream; 64: try {outFile = new BufferedWriter(new OutputStreamWriter 65: (new FileOutputStream (fileName)),1000000); 66: } catch ( IOException eIO ) 67: {System.out.println("I/OError! " + fileName); 68: recNum=-1; 69: } 70: return recNum; 71: } 72: int close() 73: { 74: if (recNum > 0) 75: { 76: if (displayOn) 77: sysout.display("Close Output: " + u.padLeft(recNum,10) 78: + " Records: "+ fileName 79: +" "); 80: 81: //1.0 try {outFileStream.close(); // free up resource 82: try {outFile.close(); // free up resource 83: }catch ( IOException eIO ) 84: {System.out.println("I/OError! " + fileName); } 85: } 86: recNum = - recNum; 87: fileName = ""; 88: return recNum; 89: } 90: // 2000-07-11 add setName(String fileName) move file "open" check logic 91: // add setLine(String fileLine) to do write. 92: 93: void setName(String parmName) 94: { 95: if (!parmName.equals(fileName)) 96: { 97: open(parmName); 98: } 99: } 100: int setLine(String parmLine) 101: { 102: if (recNum >= 0) 103: { 104: try { outFile.write(parmLine); 105: outFile.newLine(); // platform dependent line separator 106: if (flushOn) outFile.flush(); // flush after each line... 107: } catch ( IOException eIO ) 108: {System.out.println("I/OError! " + fileName); } 109: } 110: recNum++; 111: return recNum; 112: } 113: void setFlush(boolean parmTF) 114: { 115: flushOn = parmTF; 116: } 117: // 2000-06-25 add following "object" method. 118: // 2000-07-11 all code moved to setName/setLine(). 119: int write(String parmName, String parmLine) 120: { 121: // if (displayOn) sysout.display("Write: " + parmName + parmLine); 122: setName(parmName); 123: return setLine(parmLine); 124: } 125: 126: // following is kept for backward compatability 127: int write(String nameRecord[]) 128: { 129: // if (displayOn) sysout.display("Write: " + nameRecord[0] + nameRecord[1]); 130: setName(nameRecord[0]); 131: return setLine(nameRecord[1]); 132: } 133: } JsrLinePlot.java 22910 Sat Jul 15 08:59:54 CDT 2000 1: //----------------------------------------------------------------------------- 2: // JsrLinePlot.java 3: // 4: // Many thanks to Kelvin R. Lawrence of IBM-Austin for his Paths sample 5: // from which I lifted all the "options" code. 6: // 7: // My contribution was to create make the program callable from another 8: // program, and add the logic to plot a variable number of lines 9: // for a variable number of points. 10: // 11: // Steve Ryder (JSR Systems) July, 2000. 12: //----------------------------------------------------------------------------- 13: // A simple example of using the new path construction facilities of Java 2D. 14: // This version requires Java JDK level 1.2 (Beta4) or higher. 15: // Demonstrates use of these classes/interfaces: 16: // Graphics2D 17: // GeneralPath 18: // Original Author : Kelvin R Lawrence. 3rd-April-1998 19: //----------------------------------------------------------------------------- 20: import java.awt.* ; 21: import java.awt.event.* ; 22: import java.awt.geom.* ; 23: 24: //--------------------------------------------------------------- 25: // Class: JsrLinePlot 26: // 27: // Simple class that uses paths to draw line plots. 28: // 29: //--------------------------------------------------------------- 30: public class JsrLinePlot extends Frame implements ItemListener, ActionListener 31: { 32: static final String COPYRIGHT = 33: "Copyright 2000, JSR Systems. See: www.Jsrsys.com/copyright."; 34: 35: private String[] plotLabel; // labels for each plotted line. 36: private int[][] plotValue; // values for each line. 37: private String[] plotOrder; // 1-10 = value @ numPoint, 11-15 = array index 38: private int maxValue; // maximum Value, all lines. 39: private int numPoint; // number of Points to plot. 40: private int numLine; // number of Lines to plot. 41: static final Color[] lineColor = 42: {Color.red, Color.green, Color.blue, 43: Color.orange, Color.pink, Color.yellow, 44: Color.magenta, Color.cyan, Color.white}; 45: JsrUtil u = new JsrUtil(); // for pad Commands. 46: JsrSortString sortOrder = new JsrSortString(); 47: JsrSysout sysout = new JsrSysout(); 48: 49: static final int DEFAULT_WIDTH = 2 ; 50: static final int MAX_WIDTH = 100 ; 51: static final int MIN_WIDTH = 1 ; 52: 53: private MenuBar menuBar ; 54: private Menu menuOptions ; 55: private Menu menuEndings ; 56: private Menu menuJoinings ; 57: private Menu menuWidths ; 58: private Menu menuRender ; 59: private Menu menuBeziers ; 60: 61: private CheckboxMenuItem mitAntiAlias ; 62: private CheckboxMenuItem mitClosePath ; 63: private CheckboxMenuItem mitDashing ; 64: private CheckboxMenuItem mitOutline ; 65: 66: private CheckboxMenuItem mitJoinMitre ; 67: private CheckboxMenuItem mitJoinBevel ; 68: private CheckboxMenuItem mitJoinRound ; 69: 70: private CheckboxMenuItem mitEndNone ; 71: private CheckboxMenuItem mitEndRound ; 72: private CheckboxMenuItem mitEndSquare ; 73: 74: private CheckboxMenuItem curEnding ; 75: private CheckboxMenuItem curJoining ; 76: private CheckboxMenuItem curShape ; 77: private CheckboxMenuItem curColor ; 78: 79: 80: 81: private MenuItem mitIncrease ; 82: private MenuItem mitDecrease ; 83: private MenuItem mitMaximum ; 84: private MenuItem mitMinimum ; 85: private MenuItem mitDefault ; 86: 87: private Menu menuBackCol ; 88: private CheckboxMenuItem mitColGray ; 89: private CheckboxMenuItem mitColBlack ; 90: 91: private CheckboxMenuItem mitRenderQual ; 92: private CheckboxMenuItem mitRenderFast ; 93: private CheckboxMenuItem mitRenderDef ; 94: 95: private boolean fAntiAlias ; 96: private boolean fClosePath ; 97: private boolean fDashing ; 98: private boolean fOutline ; 99: private boolean fControl ; 100: 101: private int endStyle ; 102: private int joinStyle ; 103: private int lineWidth ; 104: 105: private RenderingHints hints ; 106: 107: // following added for "Select Lines that Match: "; 108: private Menu menuSelect ; 109: private MenuItem mitSelect; 110: private String mitSelX = "*"; 111: private String[] selectItems = new String[] {"*", "S", "T", "D"}; 112: // if this string is null, then Select Menu won't be built. 113: 114: //---------------------------------------------------------- 115: // Constructor 116: // 117: //---------------------------------------------------------- 118: public JsrLinePlot( String s ) 119: { 120: super(s); // I don't know why this line is here (JSR). 121: 122: enableEvents( AWTEvent.WINDOW_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK ) ; 123: 124: menuBar = new MenuBar() ; 125: 126: //---------------------------------------- 127: // Construct the "Options" menu, including 128: // the Width sub menu and rendering sub 129: // menu. 130: //---------------------------------------- 131: menuOptions = new Menu( "Options" ) ; 132: 133: mitAntiAlias = new CheckboxMenuItem( "Use Anti aliasing" ) ; 134: mitAntiAlias.setState(true); // turn on 135: mitClosePath = new CheckboxMenuItem( "Close the path" ) ; 136: mitDashing = new CheckboxMenuItem( "Dashed lines" ) ; 137: mitOutline = new CheckboxMenuItem( "Draw outline" ) ; 138: 139: 140: menuWidths = new Menu( "Line Widths" ) ; 141: 142: mitIncrease = new MenuItem( "Increase (+5)" ) ; 143: mitDecrease = new MenuItem( "Decrease (-5)" ) ; 144: mitMaximum = new MenuItem( "Maximum" ) ; 145: mitMinimum = new MenuItem( "Minimum" ) ; 146: mitDefault = new MenuItem( "Default" ) ; 147: 148: menuBackCol = new Menu( "Background colour" ) ; 149: mitColGray = new CheckboxMenuItem( "Gray" ) ; 150: mitColBlack = new CheckboxMenuItem( "Black" ) ; 151: 152: menuBackCol.add( mitColBlack ) ; 153: menuBackCol.add( mitColGray ) ; 154: 155: mitColBlack.addItemListener( this ) ; 156: mitColGray.addItemListener( this ) ; 157: 158: menuRender = new Menu( "Rendering" ) ; 159: 160: mitRenderDef = new CheckboxMenuItem( "Default" ) ; 161: mitRenderQual = new CheckboxMenuItem( "Quality" ) ; 162: mitRenderFast = new CheckboxMenuItem( "Fastest" ) ; 163: 164: menuWidths.add( mitIncrease ) ; 165: menuWidths.add( mitDecrease ) ; 166: menuWidths.add( mitMaximum ) ; 167: menuWidths.add( mitMinimum ) ; 168: menuWidths.add( mitDefault ) ; 169: 170: menuRender.add( mitRenderDef ) ; 171: menuRender.add( mitRenderQual ) ; 172: menuRender.add( mitRenderFast ) ; 173: 174: menuOptions.add( mitAntiAlias ) ; 175: menuOptions.add( mitClosePath ) ; 176: menuOptions.add( mitDashing ) ; 177: menuOptions.add( mitOutline ) ; 178: menuOptions.add( menuWidths ) ; 179: menuOptions.add( menuRender ) ; 180: 181: menuOptions.add( menuBackCol ) ; 182: 183: mitAntiAlias.addItemListener( this ) ; 184: mitClosePath.addItemListener( this ) ; 185: mitDashing.addItemListener( this ) ; 186: mitOutline.addItemListener( this ) ; 187: 188: mitIncrease.addActionListener( this ) ; 189: mitDecrease.addActionListener( this ) ; 190: mitMaximum.addActionListener( this ) ; 191: mitMinimum.addActionListener( this ) ; 192: mitDefault.addActionListener( this ) ; 193: 194: mitRenderDef.addItemListener( this ) ; 195: mitRenderQual.addItemListener( this ) ; 196: mitRenderFast.addItemListener( this ) ; 197: 198: //------------------------------ 199: // Construct the "Endings" menu. 200: //------------------------------ 201: menuEndings = new Menu( "Endings" ) ; 202: 203: mitEndNone = new CheckboxMenuItem( "None" ) ; 204: mitEndSquare = new CheckboxMenuItem( "Square" ) ; 205: mitEndRound = new CheckboxMenuItem( "Round" ) ; 206: 207: menuEndings.add( mitEndNone ) ; 208: menuEndings.add( mitEndSquare ) ; 209: menuEndings.add( mitEndRound ) ; 210: 211: mitEndNone.addItemListener( this ) ; 212: mitEndSquare.addItemListener( this ) ; 213: mitEndRound.addItemListener( this ) ; 214: 215: //------------------------------ 216: //Construct the "Joinings" menu. 217: //------------------------------ 218: menuJoinings = new Menu( "Joinings" ) ; 219: 220: mitJoinBevel = new CheckboxMenuItem( "Bevel" ) ; 221: mitJoinMitre = new CheckboxMenuItem( "Mitre" ) ; 222: mitJoinRound = new CheckboxMenuItem( "Round" ) ; 223: 224: menuJoinings.add( mitJoinBevel ) ; 225: menuJoinings.add( mitJoinMitre ) ; 226: menuJoinings.add( mitJoinRound ) ; 227: 228: mitJoinBevel.addItemListener( this ) ; 229: mitJoinMitre.addItemListener( this ) ; 230: mitJoinRound.addItemListener( this ) ; 231: 232: //--------------------------------------------------- 233: // Add the menus to the menu bar and add the menu bar 234: // to the frame. 235: //--------------------------------------------------- 236: menuBar.add( menuOptions ) ; 237: menuBar.add( menuEndings ) ; 238: menuBar.add( menuJoinings ) ; 239: 240: 241: setMenuBar( menuBar ) ; 242: 243: //--------------------------- 244: // Initialise a few settings. 245: //--------------------------- 246: 247: fAntiAlias = true ; 248: fClosePath = false ; 249: fDashing = false ; 250: fOutline = false ; 251: fControl = true ; 252: 253: endStyle = BasicStroke.CAP_ROUND ; 254: joinStyle = BasicStroke.JOIN_MITER ; 255: 256: mitJoinMitre.setState( true ) ; 257: mitEndRound.setState( true ) ; 258: mitColBlack.setState( true ) ; 259: 260: curEnding = mitEndRound ; 261: curJoining = mitJoinMitre ; 262: curColor = mitColBlack ; 263: 264: lineWidth = DEFAULT_WIDTH ; 265: 266: //------------------------------------------ 267: // Setup our default set of rendering hints. 268: //------------------------------------------ 269: hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING 270: , RenderingHints.VALUE_ANTIALIAS_OFF ) ; 271: 272: hints.put( hints.KEY_RENDERING, hints.VALUE_RENDER_DEFAULT ) ; 273: 274: mitRenderDef.setState( true ) ; 275: } 276: 277: //------------------------------------------------------------------------- 278: // paint() 279: // 280: //------------------------------------------------------------------------- 281: public void paint( Graphics g ) 282: { 283: //System.out.println("Enter paint."); 284: //System.out.println("Len="+numLine+"/"+numPoint); 285: //System.out.println("Label[0]="+plotLabel[0]); 286: //for (int i=0; i < plotValue[0].length; i++) 287: // System.out.print(plotValue[0][i]+"/"); 288: //System.out.println("."); 289: 290: Font labelFont = new Font("SansSerif",Font.BOLD,12); 291: 292: Dimension d = getSize() ; 293: Insets ins = getInsets() ; 294: 295: Graphics2D g2d = (Graphics2D) g ; 296: g2d.setFont(labelFont); 297: 298: if ( curColor.equals( mitColBlack )) 299: { 300: g2d.setColor( Color.black ) ; 301: } 302: else 303: { 304: g2d.setColor( Color.lightGray ) ; 305: } 306: 307: g2d.fillRect( 0,0,d.width,d.height ) ; 308: 309: //------------------------------------- 310: // Set the appropriate rendering hints. 311: //------------------------------------- 312: 313: if ( fAntiAlias ) 314: { 315: //g2d.setRenderingHints( g2d.ANTIALIASING, g2d.ANTIALIAS_ON ) ; 316: //hints.put( hints.KEY_ANTIALIASING, hints.VALUE_ANTIALIAS_ON ) ; 317: g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ) ; 318: } 319: else 320: { 321: //g2d.setRenderingHints( g2d.ANTIALIASING, g2d.ANTIALIAS_OFF ) ; 322: //hints.put( hints.KEY_ANTIALIASING, hints.VALUE_ANTIALIAS_OFF ) ; 323: g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF ) ; 324: } 325: 326: //g2d.setRenderingHints( hints ) ; 327: //System.out.println( hints.toString() ) ; 328: 329: //---------------------- 330: // Create a simple path. 331: //---------------------- 332: long time1 = System.currentTimeMillis() ; 333: 334: int xStart = 100 ; int yStart = 100 ; 335: 336: // need to "convert" plotValue(s) to points scaled by d.width, d.height. JSR 337: float beginY = d.height*15/16; // Y is up/down(Values). 338: float beginX = d.width*1/16; // X is across (numPoint) 339: float scaleX = d.width*2/3/numPoint; // pixels across each iteration. 340: float scaleY = (beginY-60)/maxValue; // pixels each value? 341: // need to leave 60 pixels at top for title & menu lines. 342: 343: //sysout.display(scaleY+"/"+d.height+"/"+beginY+ 344: // "<--scaleY/d.height/beginY"); 345: float thisX = 0; 346: float thisY = 0; // to save last plotted point for label. 347: //int lastY = 99999; // last label loc, to avoid overlap. (if going bottom to top) 348: float lastY = 0; // if going top to bottom 349: for (int iOrder = numLine-1; iOrder >= 0; iOrder--) 350: { 351: // do in order, lowest to highest so can adjust overlapping labels 352: int i = u.getInt(plotOrder[iOrder].substring(10)); 353: //sysout.display("plotLabel[i]="+plotLabel[i].substring(0,1)); 354: if (!mitSelX.equals("*") && 355: (!mitSelX.equals(plotLabel[i].substring(0,mitSelX.length()))) ) 356: continue; // break out of this iteration if not desired line 357: 358: //System.out.println("Plotting i="+i+" plotOrder: "+plotOrder[iOrder]); 359: // loop to plot lines 360: GeneralPath path = new GeneralPath() ; 361: 362: // will plot the line(s) here... 363: path.moveTo( beginX,beginY ); 364: for (int b=0; b < numPoint; b++) 365: { 366: thisX = beginX+(scaleX*(b+1)); 367: thisY = beginY-(scaleY*plotValue[i][b]); 368: path.lineTo( thisX, thisY); 369: } 370: 371: //----------------------------------------- 372: // Close the path if requested by the user. 373: //----------------------------------------- 374: 375: if ( fClosePath ) path.closePath() ; 376: 377: //----------------------------------------------------------- 378: // Now make a few modifications to the path and "stroke" it. 379: // 380: //----------------------------------------------------------- 381: 382: float [] dash = { 30, 5 } ; 383: 384: BasicStroke bs ; 385: 386: if ( fDashing ) 387: { 388: bs = new BasicStroke( (float)lineWidth, endStyle, joinStyle, 389: 10, dash, 0 ) ; 390: } // mitreLimit, dash array, phase 391: else 392: { 393: bs = new BasicStroke( (float)lineWidth, endStyle, joinStyle ); 394: } 395: 396: //------------------------------- 397: // Now, finally, render the path. 398: //------------------------------- 399: 400: int jColor = i; 401: while (jColor >= lineColor.length) jColor -= lineColor.length; 402: g2d.setColor(lineColor[jColor]); 403: //System.out.println("i/jColor:"+i+"/"+jColor+lineColor[jColor].toString()); 404: 405: if ( fOutline ) 406: { 407: g2d.draw( bs.createStrokedShape( path ) ) ; 408: } 409: else 410: { 411: g2d.setStroke( bs ) ; 412: g2d.draw( path ) ; 413: } 414: //if (lastY==0)sysout.display("lastY="+lastY+" thisY="+thisY); 415: //if (thisY >= (lastY-15)) lastY = lastY - 15; // do this if going 416: //else lastY = thisY; // bottom to top (-). 417: if (thisY <= (lastY+15)) lastY = lastY + 15; // do this if going 418: else lastY = thisY; // top to bottom (+) 419: g2d.drawString(u.padLeft(plotValue[i][numPoint-1],5)+" "+ 420: plotLabel[i], thisX, lastY ); 421: 422: 423: // loop for each line ends here 424: } 425: long time2 = System.currentTimeMillis() ; 426: //System.out.println((time2-time1)+"<-draw time (millis) "); 427: 428: 429: } // end of paint routine 430: 431: 432: //------------------------------------------------------------------------- 433: // actionPerformed() 434: // 435: // Handle menu actions for which we have registered interest. 436: // 437: //------------------------------------------------------------------------- 438: public void actionPerformed( ActionEvent aevt ) 439: { 440: 441: if ( aevt.getSource() instanceof MenuItem ) 442: { 443: MenuItem item = (MenuItem)aevt.getSource() ; 444: if ( item.equals( mitIncrease ) ) 445: { 446: lineWidth += 5 ; 447: 448: if ( lineWidth >= MAX_WIDTH ) 449: { 450: lineWidth = MAX_WIDTH ; 451: } 452: } 453: else if ( item.equals( mitDecrease ) ) 454: { 455: lineWidth -= 5 ; 456: 457: if ( lineWidth <= MIN_WIDTH ) 458: { 459: lineWidth = MIN_WIDTH ; 460: } 461: } 462: else if ( item.equals( mitMaximum ) ) 463: { 464: lineWidth = MAX_WIDTH ; 465: } 466: else if ( item.equals( mitMinimum ) ) 467: { 468: lineWidth = MIN_WIDTH ; 469: } 470: else if ( item.equals( mitDefault ) ) 471: { 472: lineWidth = DEFAULT_WIDTH ; 473: } 474: else // all that is left is Select items... 475: { 476: String menuItem=aevt.getActionCommand(); 477: // sysout.display ("Menu: "+menuItem); 478: mitSelX = menuItem; 479: } 480: 481: } 482: 483: repaint() ; 484: } 485: 486: //------------------------------------------------------------------------- 487: // itemStateChanged() 488: // 489: // Handle menu actions for which we have registered interest. 490: // 491: //------------------------------------------------------------------------- 492: public void itemStateChanged( ItemEvent ievt ) 493: { 494: if ( ievt.getSource() instanceof CheckboxMenuItem ) 495: { 496: CheckboxMenuItem item = (CheckboxMenuItem)ievt.getSource() ; 497: 498: if ( item.equals( mitAntiAlias ) ) 499: { 500: fAntiAlias = item.getState() ; 501: } 502: else if ( item.equals( mitClosePath ) ) 503: { 504: fClosePath = item.getState() ; 505: } 506: else if ( item.equals( mitDashing ) ) 507: { 508: fDashing = item.getState() ; 509: } 510: else if ( item.equals( mitOutline ) ) 511: { 512: fOutline = item.getState() ; 513: } 514: else if ( item.equals( mitEndRound ) ) 515: { 516: curEnding.setState( false ) ; 517: endStyle = BasicStroke.CAP_ROUND ; 518: curEnding = item ; 519: item.setState( true ) ; 520: } 521: else if ( item.equals( mitEndSquare ) ) 522: { 523: curEnding.setState( false ) ; 524: endStyle = BasicStroke.CAP_SQUARE ; 525: curEnding = item ; 526: item.setState( true ) ; 527: } 528: else if ( item.equals( mitEndNone ) ) 529: { 530: curEnding.setState( false ) ; 531: endStyle = BasicStroke.CAP_BUTT ; 532: curEnding = item ; 533: item.setState( true ) ; 534: } 535: else if ( item.equals( mitJoinBevel ) ) 536: { 537: curJoining.setState( false ) ; 538: joinStyle = BasicStroke.JOIN_BEVEL ; 539: curJoining = item ; 540: item.setState( true ) ; 541: } 542: else if ( item.equals( mitJoinMitre ) ) 543: { 544: curJoining.setState( false ) ; 545: joinStyle = BasicStroke.JOIN_MITER ; 546: curJoining = item ; 547: item.setState( true ) ; 548: } 549: else if ( item.equals( mitJoinRound ) ) 550: { 551: curJoining.setState( false ) ; 552: joinStyle = BasicStroke.JOIN_ROUND ; 553: curJoining = item ; 554: item.setState( true ) ; 555: } 556: else if ( item.equals( mitRenderDef ) ) 557: { 558: //renderMode = Graphics2D.RENDER_DEFAULT ; 559: hints.put( hints.KEY_RENDERING, hints.VALUE_RENDER_DEFAULT ) ; 560: } 561: else if ( item.equals( mitRenderQual ) ) 562: { 563: //renderMode = Graphics2D.RENDER_QUALITY ; 564: hints.put( hints.KEY_RENDERING, hints.VALUE_RENDER_QUALITY ) ; 565: } 566: else if ( item.equals( mitRenderFast ) ) 567: { 568: //renderMode = Graphics2D.RENDER_SPEED ; 569: hints.put( hints.KEY_RENDERING, hints.VALUE_RENDER_SPEED ) ; 570: } 571: else if ( item.equals( mitColBlack ) || item.equals( mitColGray )) 572: { 573: curColor.setState( false ) ; 574: curColor = item ; 575: item.setState( true ) ; 576: } 577: 578: repaint() ; 579: } 580: } 581: 582: // When winddow is closed. 583: class WindowExit extends WindowAdapter 584: { 585: public void windowClosing(WindowEvent e) 586: { 587: Window w = e.getWindow(); 588: w.setVisible(false); 589: w.dispose(); 590: sysout.display("JsrLinePlot--Exiting"); 591: } 592: } 593: // end class WindowExit 594: // Note: this must be defined physically in the class 595: // BEFORE the first reference. When I defined it at 596: // the end, it was not found, I moved it up here, all OK! 597: 598: 599: // drawLinePlot() entry from another class 600: 601: public void drawLinePlot (String titleTxt, String[] lineLabel, int[][] lineValue, 602: String[] lineSelect) 603: { 604: sysout.display("Enter JsrLinePlot: "+ 605: "Len="+lineLabel.length+"/"+lineValue.length+ 606: "/"+lineValue[0].length+"/"+lineLabel[0]); 607: // assign values to instance variables needed for plot. 608: //JsrLinePlot f ; 609: //f = new JsrLinePlot( titleTxt ) ; 610: this.addWindowListener(new WindowExit()); 611: this.setTitle(titleTxt); 612: if (lineSelect.length > 0) // add this menu item only if have array. 613: { 614: this.selectItems = lineSelect; 615: this.menuSelect = new Menu( "Select Lines that Match: " ); 616: 617: for (int i=0; i < this.selectItems.length; i++) 618: { 619: this.mitSelect = new MenuItem(this.selectItems[i]); 620: this.mitSelect.addActionListener(this); 621: this.menuSelect.add(this.mitSelect); 622: } 623: this.menuBar.add( this.menuSelect ); 624: 625: this.setMenuBar( this.menuBar ) ; 626: } 627: 628: // must set this. values to get correct instance of JsrLinePlot for paint. 629: // without the this. is setting instance created by calling class. 630: this.numPoint = lineValue[0].length; 631: this.numLine = lineValue.length; 632: this.plotLabel = lineLabel; // sets whole array 633: this.plotValue = lineValue; // sets whole array 634: this.maxValue = 0; 635: this.plotOrder = new String[this.numLine]; 636: //System.out.println("Len="+this.numLine+"/"+this.numPoint+"/"+this.plotLabel[0]); 637: //System.out.println("lenOrder="+this.plotOrder.length); 638: for (int i=0; i < this.numLine; i++) 639: { 640: for (int b=0; b < this.numPoint; b++) 641: { 642: //System.out.print(this.plotValue[i][b]+"/"); 643: if (this.maxValue < this.plotValue[i][b]) 644: this.maxValue = this.plotValue[i][b]; 645: } 646: //System.out.print("numPoint-1="+(this.numPoint-1)+"/"); 647: //System.out.println("lastValue="+this.plotValue[i][this.numPoint-1]); 648: //System.out.println(u.padZero(this.plotValue[i][this.numPoint-1],10)+u.padZero(i,5)); 649: 650: this.plotOrder[i] = u.padZero(this.plotValue[i][this.numPoint-1],10)+u.padZero(i,5); 651: //System.out.println("plotOrder[...]: "+this.plotOrder[i]); 652: } 653: //System.out.println("\r\nMax="+this.maxValue+"."); 654: try{sortOrder.sort(this.plotOrder);} // sorts array in place. 655: catch (Exception Sort) {System.out.println("Sort Error in JsrLinePlot!");} 656: //System.out.println("Sort: "+this.plotOrder[0]+"/"+this.plotOrder[1]); 657: 658: Toolkit tlkt = Toolkit.getDefaultToolkit() ; 659: Dimension dim = tlkt.getScreenSize() ; 660: this.setBounds( dim.width*1/16,dim.height*1/16,dim.width*7/8,dim.height*7/8 ); 661: // above will leave a 1/16 border around a window that fills 7/8 of the screen. 662: this.show() ; 663: //return; -- closes with window listener. 664: } 665: //--end of class JsrLinePlot 666: } . JsrPrint1.java 6403 Wed Sep 15 22:00:36 CDT 1999 1: import java.io.PrintWriter; 2: import java.io.FileWriter; 3: import java.io.IOException; 4: 5: class JsrPrint1 6: { 7: 8: static final String COPYRIGHT = 9: "Copyright 1999, JSR Systems. See: www.Jsrsys.com/copyright."; 10: 11: static JsrSysout sysout = new JsrSysout(); 12: static JsrUtil u = new JsrUtil(); 13: static String[] inputFile = {" ", " "}; 14: static JsrLineIn input = new JsrLineIn(); 15: static int lineCount = 0; 16: static int pageCount = 0; 17: // default printer is "old style" ASCII 18: static boolean hplj = false; // 17 cpi 19: static boolean hplj20= false; // 20 cpi 20: static boolean hpdj = false; // 24 cpi 21: static boolean brotherHL = false; // 17 cpi 22: static boolean cc = true; // default is cc (nocc sets to false) 23: static String ccChar = " "; 24: static int linesPerPage = 60; 25: public static void main(String parm[]) 26: { 27: sysout.display("JsrPrint1--"+COPYRIGHT); 28: sysout.display("JsrPrint1--usage: JsrPrint1 <input file> <printer/LPT1> <cc/nocc>"); 29: sysout.display("--------------------------- <hplj> <hplj20> <hpdj> <BrotherHL>"); 30: if (parm.length < 2) 31: { 32: sysout.display("JsrPrint1--requires two parameters"); 33: return; 34: } 35: for (int i = 2; i < parm.length; i++) 36: { 37: if (parm[i].equalsIgnoreCase("nocc")) 38: cc = false; 39: if (parm[i].equalsIgnoreCase("hplj")) // 17 cpi 40: hplj = true; 41: if (parm[i].equalsIgnoreCase("hplj20")) // 20 cpi 42: hplj20 = true; 43: if (parm[i].equalsIgnoreCase("hpdj")) // 24 cpi 44: hpdj = true; 45: if (parm[i].equalsIgnoreCase("BrotherHL")) // 17 cpi 46: brotherHL = true; 47: } 48: 49: inputFile [0] = parm[0]; 50: sysout.display("Reading from: " + inputFile[0]); 51: 52: PrintWriter out; 53: try 54: {out = new PrintWriter(new FileWriter(parm[1])); 55: } catch(IOException e) {sysout.display("Printer IO exception"+e); 56: return; 57: } 58: sysout.display("Printing to: " + parm[1]); 59: 60: if (hplj20) // HP Laser Jet @ 20 cpi 61: { 62: out.print("\033E"); // Reset to defaults (for HP printers) 63: out.print("\033&l8d&l88P"); // 8 lines per inch, 88 lpp 64: out.print("\033&l4e&l80F"); // top margin 4 lines, 80 text lines 65: out.print("\033(s0p(s20H"); // fixed pitch 20 char / inch 66: out.print("\033(s0b(s6T"); // Normal strike wt. Letter Gothic typeface 67: linesPerPage = 80; 68: } 69: else 70: if (brotherHL || hplj) // Brother HL-1040 Laser Jet or HPLJ @ 17 cpi 71: { 72: out.print("\033E"); // Reset to defaults (for HP printers) 73: out.print("\033&l8d&l88P"); // 8 lines per inch, 88 lpp 74: out.print("\033&l4e&l80F"); // top margin 4 lines, 80 text lines 75: out.print("\033(s0p(s17H"); // fixed pitch 17 char / inch 76: out.print("\033(s0b(s6T"); // Normal strike wt. Letter Gothic typeface 77: linesPerPage = 80; 78: } 79: else 80: if (hpdj) // HP Desk Jet 81: { 82: out.print("\033E"); // Reset to defaults (for HP printers) 83: out.print("\033&l6d&l66P"); // 6 lines per inch, 66 lpp 84: out.print("\033&l3e&l60F"); // top margin 3 lines, 60 text lines 85: out.print("\033(s0p(s24H"); // fixed pitch 24 char / inch 86: out.print("\033(s0b(s6T"); // Normal strike wt. Letter Gothic typeface 87: out.print("\033*o-1M"); // EconoFast 300X300 dpi 88: linesPerPage = 60; 89: } 90: else 91: { 92: out.print("\017"); // compressed print on Canon 93: linesPerPage = 59; 94: } 95: 96: int recNum = 0; 97: while (0 <= (recNum=input.read(inputFile))) 98: { 99: lineCount++; 100: if (cc) 101: { 102: if (inputFile[1].length() < 2) 103: { 104: ccChar = " "; 105: inputFile[1] = " "; 106: } 107: else 108: { 109: ccChar = inputFile[1].substring(0,1); 110: inputFile[1] = inputFile[1].substring(1); 111: } 112: if (ccChar.equals("1")) 113: { 114: if (pageCount > 0 || lineCount > 1) 115: { 116: out.print("\f"); // eject page 117: pageCount++; 118: lineCount--; 119: sysout.display("Printing page: " +pageCount + 120: " (lines on page: "+lineCount+")"); 121: lineCount = 1; 122: ccChar = " "; 123: } 124: } 125: 126: } 127: 128: if (cc && ccChar.equals("+")) lineCount--; 129: if (cc && ccChar.equals("0")) lineCount++; 130: if (cc && ccChar.equals("-")) lineCount+=2; 131: 132: // newpage if lineCount > linesPerPage, even if cc... 133: if (lineCount > linesPerPage) 134: { pageCount++; 135: out.print('\f'); // eject page 136: lineCount--; 137: sysout.display("Printing page: "+pageCount + 138: " (lines on page: "+lineCount+")"); 139: lineCount = 1; 140: } 141: if (cc) 142: { 143: if (ccChar.equals("+")) out.print("\r"); 144: else 145: if (ccChar.equals("0")) out.print("\r\n\r\n"); 146: else 147: if (ccChar.equals("-")) out.print("\r\n\r\n\r\n"); 148: else 149: out.print("\r\n"); 150: 151: out.print(inputFile[1]); 152: } 153: else 154: out.println(inputFile[1]); 155: 156: } 157: 158: // flush and check if we got any errors from those 159: // print() and println() calls 160: if (out.checkError()) { 161: System.err.println("Got errors printing"); 162: System.exit(-1); 163: } 164: pageCount++; 165: sysout.display("Printing page: " +pageCount + 166: " (lines on page: "+lineCount+")"); 167: out.print('\f'); // eject page then close stream 168: if (hplj || hpdj || brotherHL || hplj20) 169: out.print("\033E"); // Reset to defaults 170: 171: out.flush(); // not needed; close() will flush 172: out.close(); 173: } 174: } JsrSortString.java 2151 Thu Aug 20 20:30:14 CDT 1998 1: /* 2: * JsrSortString 3: */ 4: public class JsrSortString 5: { 6: static final String COPYRIGHT = 7: "Copyright 1998, JSR Systems. See: www.Jsrsys.com/copyright."; 8: /* This is a generic version of C.A.R Hoare's Quick Sort 9: * algorithm. This will handle arrays that are already 10: * sorted, and arrays with duplicate keys. 11: * 12: * @param a a String array 13: * @param lo0 left boundary of array partition 14: * @param hi0 right boundary of array partition 15: */ 16: void JsrQuickSort(String a[], int lo0, int hi0) throws Exception 17: { 18: int lo = lo0; 19: int hi = hi0; 20: String mid; 21: 22: if ( hi0 > lo0) 23: { 24: 25: // Arbitrarily establishing partition element at the midpoint. 26: mid = a[ ( lo0 + hi0 ) / 2 ]; 27: 28: // loop through the array until indices cross 29: while( lo <= hi ) 30: { 31: // find the first element that is greater than or equal to 32: // the partition element starting from the left Index. 33: while( ( lo < hi0 ) && ( a[lo].compareTo(mid) < 0 )) 34: ++lo; 35: 36: // find an element that is smaller than or equal to 37: // the partition element starting from the right Index. 38: while( ( hi > lo0 ) && ( a[hi].compareTo(mid) > 0 )) 39: --hi; 40: 41: // if the indexes have not crossed, swap 42: if( lo <= hi ) 43: { 44: swap(a, lo, hi); 45: ++lo; 46: --hi; 47: } 48: } 49: 50: // If the right index has not reached the left side of array 51: // must now sort the left partition. 52: if( lo0 < hi ) 53: JsrQuickSort( a, lo0, hi ); 54: 55: /* If the left index has not reached the right side of array 56: * must now sort the right partition. 57: */ 58: if( lo < hi0 ) 59: JsrQuickSort( a, lo, hi0 ); 60: 61: } 62: } 63: 64: private void swap(String a[], int i, int j) 65: { 66: String T; 67: T = a[i]; 68: a[i] = a[j]; 69: a[j] = T; 70: 71: } 72: 73: public void sort(String a[]) throws Exception 74: { 75: JsrQuickSort(a, 0, a.length - 1); 76: } 77: } JsrUtil.java 7314 Sat Jul 08 10:34:28 CDT 2000 1: /****************************************************************************** 2: // JsrUtil.java: padLeft, padRight, string or integer input. 3: // output is padded or truncated as necessary. 4: * Sample Use: 5: * import JsrUtil; ... 6: * JsrUtil u = new JsrUtil(); 7: * paddedString = u.padLeft(oldString,10); 8: * paddedInteger = u.padLeft(oldInt,10); 9: * zeroPadInt = u.padZero(oldInt,10); 10: * paddedString = u.padRight(oldString,10); 11: * dateTime = u.getDateTime(); 12: * modString = u.replaceAll(inString,fromString,toString); 13: * int = u.getInt(inString); // makes String an int. 14: * 15: */ 16: import java.util.*; 17: 18: public class JsrUtil 19: { 20: static final String COPYRIGHT = 21: "Copyright 1998, JSR Systems. See: www.Jsrsys.com/copyright."; 22: static final char[] blank = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ', 23: ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ', 24: ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ', 25: ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ', 26: ' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; 27: // fifty (50) blanks for append... 28: 29: public JsrUtil() // null constructor 30: { 31: } 32: 33: String padLeft(String parmString, int parmLen) 34: { 35: String tempString; 36: int addLen; 37: StringBuffer sb = new StringBuffer(parmLen); 38: // set capacity of initial buffer to desired length! 39: if (parmString.length() > parmLen) 40: tempString = parmString.substring(parmString.length()-parmLen, 41: parmString.length()); 42: else 43: { 44: // tempString = parmString; 45: // while (tempString.length() < parmLen) 46: // tempString = " "+tempString; 47: addLen = parmLen - parmString.length(); 48: while (addLen > 50) // char[] array is only 50 blanks. 49: { 50: sb = sb.append(blank,0,50); 51: addLen -= 50; 52: } // now append final set of blanks w/ original string on end 53: tempString = sb.append(blank,0,addLen).append(parmString).toString(); 54: } 55: return tempString; 56: } 57: 58: String padLeft(int parmInt, int parmLen) 59: { 60: Integer tempInt = new Integer(parmInt); 61: String tempString = tempInt.toString(); 62: int digitLen = tempString.length(); 63: int numComma = (digitLen-1) / 3; 64: int addLen = parmLen - digitLen - numComma; 65: StringBuffer sb = new StringBuffer(parmLen); 66: if (addLen > 0) 67: { 68: while (addLen > 50) // char[] array is only 50 blanks. 69: { 70: sb = sb.append(blank,0,50); 71: addLen -= 50; 72: } // now append final set of blanks w/ original string on end 73: sb.append(blank,0,addLen).append(tempString); 74: } 75: else sb.append(tempString); 76: 77: // System.out.println("d/n/a:"+digitLen+"/"+numComma+"/"+addLen+sb); 78: int commaPos = sb.length() - 3; 79: while (numComma > 0) 80: { 81: sb.insert(commaPos,','); 82: commaPos -= 3; 83: numComma--; 84: } 85: // 2000-06-25 for integer input -only- put in ",". 86: // also, do not truncate if longer than parmLen! 87: // return padLeft(tempString, parmLen); 88: return sb.toString(); 89: } 90: 91: String padZero(int parmInt, int parmLen) 92: { 93: Integer tempInt = new Integer(parmInt); 94: String tempString = tempInt.toString(); 95: if (tempString.length() > parmLen) 96: tempString = tempString.substring(tempString.length()-parmLen, 97: tempString.length()); 98: else 99: { 100: while (tempString.length() < parmLen) 101: tempString = "0"+tempString; 102: } 103: return tempString; 104: } 105: 106: String padRight(String parmString, int parmLen) 107: { 108: String tempString; 109: int addLen; 110: StringBuffer sb = new StringBuffer(parmLen); 111: // set capacity of initial buffer to desired length! 112: if (parmString.length() > parmLen) 113: tempString = parmString.substring(0,parmLen+1); 114: else 115: { 116: //tempString = parmString; 117: //while (tempString.length() < parmLen) 118: // tempString = tempString + " "; 119: // 2000-06-24 replace above with following more efficient code 120: // above code actualy generates: 121: // tempString = new StringBuffer().append(tempString).append(" ").toString(); 122: // (i.e., a new StringBuffer is allocated, data is put into it, 123: // it is converted back to a string, for EACH character added) 124: addLen = parmLen - parmString.length(); 125: sb = sb.append(parmString); 126: while (addLen > 50) // char[] array is only 50 blanks. 127: { 128: sb = sb.append(blank,0,50); 129: addLen -= 50; 130: } // now append final set of blanks 131: tempString = sb.append(blank,0,addLen).toString(); 132: } 133: return tempString; 134: } 135: 136: String getDateTime() 137: { 138: Calendar rightNow = Calendar.getInstance(); 139: String today = rightNow.get(Calendar.YEAR)+"-"+ 140: padZero(rightNow.get(Calendar.MONTH)+1,2)+"-"+ 141: padZero(rightNow.get(Calendar.DAY_OF_MONTH),2)+"@"+ 142: padZero(rightNow.get(Calendar.HOUR_OF_DAY),2)+":"+ 143: padZero(rightNow.get(Calendar.MINUTE),2); 144: // add 1 to month because Calendar returns 0 for January!!! 145: return today; 146: } 147: 148: // replaceAll() method modifies all occurences of "from" to "to" 149: // special cases: toString = '*delete*', newString='*delete* if find fromString 150: // fromString ends in '=', replace text following '=' 151: // to first space, '>' or end-of-line. 152: // example from: 'WIDTH=' to: '' 153: // old: 'xxWIDTH=abc z' becomes: 'xxz' 154: String replaceAll(String oldString, String from, String to) 155: { 156: int lenFrom = from.length(); 157: int lenTo = to.length(); 158: String newSB = new String(); 159: char endFrom = from.charAt(lenFrom-1); 160: char numChar = ' '; 161: int where = 0; 162: int last = 0; 163: int lenOld = oldString.length(); 164: where = oldString.indexOf(from); 165: if (to.equals("*delete*") && where != -1) 166: newSB = "*delete*"; 167: else 168: { 169: while (where != -1) 170: { 171: newSB = newSB+oldString.substring(last,where)+to; 172: last = where + lenFrom; 173: if (endFrom == '=') 174: { 175: numChar = oldString.charAt(last); 176: while (numChar > ' ' && numChar != '>' && last < lenOld) 177: // skip to next white space or '>' or end of line 178: { 179: last++; 180: numChar = oldString.charAt(last); 181: //System.out.println("numChar="+numChar); 182: } 183: } 184: where = oldString.indexOf(from,last); 185: } 186: newSB = newSB+oldString.substring(last,lenOld); 187: } 188: return newSB; 189: } 190: // end of replaceAll 191: 192: // getInt(String) -- so don't have to remember how to do it. 193: int getInt( String parmNumber) 194: { 195: Integer tempInt = new Integer(parmNumber); 196: return tempInt.intValue(); 197: } 198: // end of getInt 199: 200: } JsrVote.java 29653 Tue Jul 11 17:58:28 CDT 2000 1: // JsrVote.java 2: // 3: // 2000-06-30 changes: 4: // convert read to setFile/getNext/getLine method calls. 5: // convert write to write(fileName,record) vs. write(str[2]). 6: 7: // 2000-02-15 changes: 8: // add logic for multiple races 9: // 10: // Assumptions: the following are assumed to exist, current version has 11: // no error checking, it just assumes these states. 12: // 1) p1+i.txt exists and is well formed (see share93i.txt for example). 13: // in particular # races, and # candidates is critical. 14: // 2) race title lines are in format ## title (## is max votes this race). 15: // 3) candidate lines are in format (k) Name (k is shortcut key). 16: // 4) current version only supports one race, extra loop logic will be added. 17: // however [race] variables are all arrays, only loop logic is missing. 18: // 5) p1+v.txt is assumed to always exist. 19: // first line is assumed to be titles (for Excel). 20: // first action (ALWAYS) is to rename p1+v.txt to p1+v.$$$ 21: // then program reads p1+v.$$$, copying to p1+v.txt, 22: // building vote count (batch and total) arrays. 23: // 6) after initial run, contents of p1+i.txt must NOT be changed, except: 24: // title line, maximum batches (used for array size calculation), and 25: // batch size may be changed. 26: // 7) each ballot voted is immediately written to p1+v.txt, so recovery 27: // is always to last ballot voted. However, ballot # is part of data 28: // so recovery could be modified by editing p1+v.txt file. 29: 30: import javax.swing.*; 31: import java.awt.*; 32: import java.awt.event.*; 33: import java.io.File; 34: import java.util.*; 35: 36: 37: public class JsrVote 38: { 39: static final String COPYRIGHT = 40: "Copyright 2000, JSR Systems. See: www.Jsrsys.com/copyright."; 41: static String[] parm; 42: JsrSysout sysout = new JsrSysout(); 43: JsrUtil u = new JsrUtil(); 44: // Font defaultFont = new Font("Lucida Sans",Font.BOLD,18); 45: Font defaultFont = new Font("Comic Sans MS",Font.BOLD,18); 46: 47: // String[] inputFile = {" ", " "}; 48: String inputFileName = ""; 49: String inputLine = ""; 50: JsrLineIn input = new JsrLineIn(); 51: 52: String outputFileName = ""; 53: JsrLineOut output = new JsrLineOut(); 54: 55: String reportFileName = ""; 56: JsrLineOut report = new JsrLineOut(); 57: 58: String[] print1Parm = new String[] {"*r.txt", "LPT1", "cc", " "}; 59: JsrPrint1 print1 = new JsrPrint1(); 60: int printLPP = 66; // lines per page 61: int lineCount = 999; // line count to force immediate page break 62: 63: String voteTitle; // Title (card input) 64: int maxBatch = 0; // max # batches (card input) 65: int batchSize = 0; // batch size (card input) 66: int maxRace = 0; // max # Races (card input) 67: int maxVote = 0; // max # Votes (card input, all Races) 68: JLabel batHead = new JLabel("Batch # 1 ",SwingConstants.RIGHT); 69: JLabel totHead = new JLabel("Vote Totals",SwingConstants.RIGHT); 70: JLabel dotLabel1 = new JLabel("Race(s) & Candidates",SwingConstants.LEFT); 71: JLabel dotLabel2 = new JLabel(" ",SwingConstants.RIGHT); 72: JLabel dotLabel3 = new JLabel(" ",SwingConstants.RIGHT); 73: JLabel batSumLabel = new JLabel("Batch: xxxxxxxxx",SwingConstants.RIGHT); 74: JLabel totSumLabel = new JLabel("Total: xxxxxxxxx",SwingConstants.RIGHT); 75: 76: // for following arrays, actual allocation size will be determined in main 77: int[] voteMax; // Max # votes/Race (card input) 78: String[] raceName; // Race Name (card input) 79: String[] voteName; // Candidate name (card input) 80: // (#) name... where # is selection key (sets box true) 81: int[] raceVotes; // # votes this Ballot by Race 82: int[] voteCount; // # votes by candidate 83: int[] cummCount; // cumm votes for All Batch report (or plots). 84: int[] voteRace; // Race index by candidate 85: char[] voteArray; // the votes for this Ballot 86: int voteBallot = 0; // total Ballots 87: int b = 0; // current batch # 88: int cummBallot; // cumm ballot for All Batch report (or plots). 89: int[] batchBallot; // # ballots per batch 90: int[][] batchVote; // votes per batch 91: int[][] lineValue; // cumm votes for JsrLinePlot. 92: String[] lineLabel; // label for plot line R.name... 93: String[] lineSelect; // for plot selection by first character or Label 94: JLabel [] raceLabel1; // = new JLabel[maxRace]; 95: JLabel [] raceLabel2; // = new JLabel[maxRace]; 96: JLabel [] raceLabel3; // = new JLabel[maxRace]; 97: JCheckBox [] voteBox; // = new JCheckBox[maxVote]; 98: JLabel [] totLabel; // = new JLabel[maxVote]; 99: JLabel [] batLabel; // = new JLabel[maxVote]; 100: boolean printOn = false; // print reports? 101: String today; // set by MenuAction Listener 102: JsrLinePlot linePlot = new JsrLinePlot("requiredString"); 103: 104: JFrame frame; 105: 106: //notes on static and final: ----------------------------------------------- 107: // static means it is a class variable, not an instance variable. 108: // static means it can be accessed from any method (static or instance) 109: // final means it can not be changed, however if it is an array, 110: // then the individual array values can be changed. 111: // only final variables can be accessed from the "inner" classes. 112: // ------------------------------------------------------------------------ 113: 114: public static void main(String[] argv) 115: { 116: parm = argv; 117: JsrVote voteRun = new JsrVote(); 118: voteRun.init(); 119: } 120: 121: void init() 122: { 123: Integer tempInt; 124: sysout.syslog("syslog.txt"); 125: sysout.setNoStop(); 126: 127: sysout.display("JsrVote--"+COPYRIGHT); 128: sysout.display("JsrVote--Font: "+defaultFont.toString()); 129: if (parm.length < 1) 130: { sysout.display("JsrVote-must contain one argument:"); 131: sysout.display("--------parm 1: file prefixy (i.e., 'share95')"); 132: return; 133: } 134: inputFileName = parm[0]+"i.txt"; // input "INI" file 135: reportFileName = parm[0]+"r.txt"; // report file 136: print1Parm [0] = reportFileName; // print from report file 137: input.setName(inputFileName); // opens ...i.txt 138: input.getNext(); inputLine = input.getLine(); 139: while (inputLine.substring(0,1).equals("=")) 140: { 141: if (inputLine.substring(0,10).equals("=printNAM ")) 142: { 143: print1Parm[1] = inputLine.substring(10); 144: sysout.display("JsrVote--printNAM: "+print1Parm[1]); 145: } 146: if (inputLine.substring(0,10).equals("=printTYP ")) 147: { 148: print1Parm[3] = inputLine.substring(10); 149: sysout.display("JsrVote--printTYP: "+print1Parm[3]); 150: } 151: if (inputLine.substring(0,10).equals("=printLPP ")) 152: { 153: tempInt = new Integer(inputLine.substring(10,13)); 154: printLPP = tempInt.intValue(); 155: sysout.display("JsrVote--printLPP="+printLPP); 156: } 157: input.getNext(); inputLine = input.getLine(); 158: } 159: 160: voteTitle = inputLine; 161: sysout.display("JsrVote--Title: "+voteTitle); 162: input.getNext(); inputLine = input.getLine(); 163: tempInt = new Integer(inputLine.substring(0,3)); 164: maxBatch = tempInt.intValue(); 165: sysout.display("JsrVote--maxBatch: "+maxBatch); 166: input.getNext(); inputLine = input.getLine(); 167: tempInt = new Integer(inputLine.substring(0,2)); 168: batchSize = tempInt.intValue(); 169: sysout.display("JsrVote--batchSize: "+batchSize); 170: input.getNext(); inputLine = input.getLine(); 171: tempInt = new Integer(inputLine.substring(0,2)); 172: maxRace = tempInt.intValue(); 173: sysout.display("JsrVote--maxRace: "+maxRace); 174: input.getNext(); inputLine = input.getLine(); 175: tempInt = new Integer(inputLine.substring(0,2)); 176: maxVote = tempInt.intValue(); 177: sysout.display("JsrVote--maxVote: "+maxVote); 178: 179: // the following are (class) variables, accessible from inner classes 180: // and from all methods. They are declared at top of class, then 181: // their actual allocation size determined after size parameters are input. 182: voteMax = new int[maxRace]; // Max # votes/Race (card input) 183: raceName = new String[maxRace]; // Race Name (card input) 184: voteName = new String[maxVote]; // Candidate name (card input) 185: lineLabel = new String[maxVote];; // label for plot line R.name... 186: lineSelect = new String[(maxRace+1)]; // selection by Label 187: lineSelect[0] = "*"; // first entry should be "*" for Select All. 188: raceVotes = new int[maxRace]; // # votes this Ballot by Race 189: voteCount = new int[maxVote]; // # votes by candidate 190: cummCount = new int[maxVote]; // # votes by candidate 191: voteRace = new int[maxVote]; // Race index by candidate 192: voteArray = new char[maxVote]; // the votes for this Ballot 193: 194: batchBallot = new int[maxBatch]; // # ballots per batch 195: batchVote = new int[maxBatch][maxVote]; // votes per batch 196: 197: // sysout.display("Initializing b="+b); 198: batchBallot[b] = 0; 199: for (int i=0; i < maxVote; i++) batchVote[b][i] = 0; 200: 201: raceLabel1 = new JLabel[maxRace]; 202: raceLabel2 = new JLabel[maxRace]; 203: raceLabel3 = new JLabel[maxRace]; 204: voteBox = new JCheckBox[maxVote]; 205: totLabel = new JLabel[maxVote]; 206: batLabel = new JLabel[maxVote]; 207: 208: for (int i = 0; i < maxRace; i++) 209: { 210: raceVotes[i] = 0; 211: raceName[i] = " "; 212: } 213: int ir = -1; // individual race counter! 214: 215: for (int iv = 0; iv < maxVote; iv++) 216: { 217: input.getNext(); inputLine = input.getLine(); 218: // add checking for input file and race change 219: // sysout.display("Input: "+inputLine+"***"); 220: if (!(inputLine.substring(0,1).equals("("))) 221: { 222: tempInt = new Integer(inputLine.substring(0,2)); 223: ir++; 224: voteMax[ir] = tempInt.intValue(); 225: raceName[ir] = inputLine.substring(4); 226: lineSelect[ir+1] = raceName[ir].substring(0,1)+"-"; 227: 228: sysout.display("JsrVote--voteMax["+ir+"]: " + voteMax[ir] + 229: " raceName["+ir+"]: " + raceName[ir]); 230: input.getNext(); inputLine = input.getLine(); 231: } // can't have two ##Race Name in a row, 232: // so next card is assumed to be in (k) Candidate Name format 233: voteName[iv] = inputLine; 234: sysout.display("JsrVote--Candidate: " + voteName[iv] 235: +" Race: " + raceName[ir]); 236: voteRace[iv] = ir; 237: lineLabel[iv] = raceName[ir].substring(0,1)+"-"+inputLine.substring(4); 238: } 239: // ini file finished, now set up frame 240: 241: // A simple WindowClosing Listener 242: class VoteWindowExit extends WindowAdapter 243: { 244: public void windowClosing(WindowEvent e) 245: { 246: Window w = e.getWindow(); 247: w.setVisible(false); 248: w.dispose(); 249: sysout.display("JsrVote--Exiting"); 250: output.close(); 251: sysout.close(); 252: 253: System.exit(0); 254: } 255: } 256: // end class VoteWindowExit 257: // Note: this must be defined physically in the class 258: // BEFORE the first reference. When I defined it at 259: // the end, it was not found, I moved it up here, all OK! 260: 261: 262: try { UIManager.setLookAndFeel( 263: UIManager.getSystemLookAndFeelClassName()); 264: } catch (Exception e) { } // set Look and Feel to Windows 265: // System=Windows on Win32 systems, CrossPlatform=Metal (Java default) 266: // on other systems, presumably will be that system's look and feel. 267: 268: frame = new JFrame(voteTitle); 269: frame.addWindowListener(new VoteWindowExit()); 270: frame.setBounds(100,50,0,0); // offset right, offset down; size as needed. 271: // System.out.println("Frame created "); 272: 273: // A simple menu class w/ Action listener (see page 419-420 Java Swing) 274: class VoteMenuListener extends JMenuBar implements ActionListener 275: { 276: String[] fileItems = new String[] {"Exit"}; 277: char[] fileShortCuts = {'x'}; 278: String[] reportItems = new String[] {"This Batch", 279: "All Batches", 280: "Plot Votes"}; 281: char[] reportShortCuts = {'T','A','P'}; 282: public VoteMenuListener() // constructor 283: { 284: JMenuItem fileItem; 285: JMenu fileMenu = new JMenu("File"); 286: fileMenu.setMnemonic('F'); 287: for (int i=0; i < fileItems.length; i++) 288: { 289: fileItem = new JMenuItem(fileItems[i], fileShortCuts[i]); 290: fileItem.addActionListener(this); 291: fileMenu.add(fileItem); 292: } 293: add(fileMenu); 294: JMenuItem reportItem; 295: JMenu reportMenu = new JMenu("Reports"); 296: reportMenu.setMnemonic('R'); 297: for (int i=0; i < reportItems.length; i++) 298: { 299: reportItem = new JMenuItem(reportItems[i], reportShortCuts[i]); 300: reportItem.addActionListener(this); 301: reportMenu.add(reportItem); 302: } 303: reportMenu.add(reportItem = new JCheckBoxMenuItem("Print On/Off")); 304: reportItem.addActionListener(this); 305: add(reportMenu); 306: } 307: public void actionPerformed(ActionEvent menuEvent) 308: { 309: String menuItem=menuEvent.getActionCommand(); 310: // will do report logic from here 311: Calendar rightNow = Calendar.getInstance(); 312: today = u.getDateTime(); 313: if (menuItem.equals("Print On/Off")) printOn = !printOn; 314: // intuit printOn value rather than generate ItemListener 315: System.out.println("Menu="+ menuItem+" printOn/Off="+printOn+" "+today); 316: if (menuItem.equals("This Batch")) doThisReport(); 317: if (menuItem.equals("All Batches")) doAllReport(); 318: if (menuItem.equals("Plot Votes")) doPlotVotes(); 319: if (menuItem.equals("Exit")) 320: { 321: sysout.display("JsrVote--Exiting"); 322: output.close(); 323: sysout.close(); 324: System.exit(0); 325: } 326: } 327: } // end class VoteMenuListener 328: 329: 330: // A simple ActionListener. 331: class VoteActionListener implements ActionListener 332: { 333: public void actionPerformed(ActionEvent ex) 334: { 335: String choice = ex.getActionCommand(); 336: Integer vInteger = new Integer(choice); 337: int v = vInteger.intValue(); 338: System.out.println("ACTION Candidate[" + choice + "] Selected!"); 339: voteBox[v].setSelected(true); 340: // the above invokes itemStateChanged if it is a change 341: } 342: } // end class VoteActionListener 343: 344: // A simple ItemListener, showing each selection and deselection. 345: class VoteItemListener implements ItemListener 346: { 347: public void itemStateChanged(ItemEvent ex) 348: { 349: String item = 350: ((AbstractButton)ex.getItemSelectable()).getActionCommand(); 351: 352: boolean selected = (ex.getStateChange() == ItemEvent.SELECTED); 353: Integer vInteger = new Integer(item); 354: int v = vInteger.intValue(); 355: if (selected) 356: { 357: // System.out.println("voteArray[v]="+voteArray[v]+ "true"); 358: if (voteArray[v] == '0') 359: { 360: if (raceVotes[voteRace[v]] == voteMax[voteRace[v]]) 361: { 362: JOptionPane.showMessageDialog(frame, 363: "Maximum Votes this Race = "+voteMax[voteRace[v]]); 364: voteBox[v].setSelected(false); 365: } 366: else 367: { 368: voteArray[v] = '1'; 369: raceVotes[voteRace[v]]++; 370: } 371: } 372: } 373: else 374: { 375: // System.out.println("voteArray[v]="+voteArray[v]+ "false"); 376: if (voteArray[v] == '1') 377: { 378: voteArray[v] = '0'; 379: raceVotes[voteRace[v]]--; 380: } 381: } 382: String voteString = ""; 383: for (int i = 0; i < maxVote; i++) voteString += voteArray[i]+","; 384: 385: System.out.println(" ITEM C[" + item + "]:" + 386: " V=" + voteString + "* On/off=" + selected + 387: " #race=" + raceVotes[voteRace[v]] + 388: " " + voteName[v]); 389: } 390: } // end class VoteItemListener 391: 392: 393: 394: // p1+i.txt Initialization file read 395: // following renames will only work if files are closed (OK here, see JsrEdit.java). 396: inputFileName = parm[0]+"v.$$$"; 397: outputFileName = parm[0]+"v.txt"; 398: File txtFD = new File(outputFileName); 399: File tempFD = new File( inputFileName); 400: if (txtFD.exists() != true) 401: { 402: sysout.display("JsrVote--File: "+outputFileName+" does not exist!"); 403: System.exit(4); 404: } 405: if (tempFD.exists() == true) 406: sysout.display("JsrVote--delete " + tempFD+"=" + tempFD.delete()); 407: sysout.display("JsrVote--rename "+txtFD+ " to " 408: + tempFD+"=" + txtFD.renameTo(tempFD)); 409: output.setName(outputFileName); 410: report.setName(reportFileName); 411: output.setFlush(true); //so output file will be complete if abort. 412: report.setFlush(true); 413: input.setName(inputFileName); // change from ...i.txt to ...v.$$$ 414: input.getNext(); inputLine = input.getLine(); // copy header line 415: if (input.getCount() == 0) 416: { 417: sysout.display("Input file is empty--aborting run"); 418: System.exit(4); 419: } 420: output.setLine(inputLine); 421: 422: String acString = " "; 423: ActionListener al = new VoteActionListener(); 424: ItemListener il = new VoteItemListener(); 425: 426: // System.out.println("Initializing constants"); 427: 428: for (int i = 0; i < maxRace; i++) 429: { 430: sysout.display("Initializing raceLabel["+ i +"]: "+raceName[i]); 431: raceLabel1[i] = new JLabel(raceName[i]); 432: raceLabel1[i].setFont(defaultFont); 433: raceLabel2[i] = new JLabel(" ",SwingConstants.RIGHT); 434: raceLabel3[i] = new JLabel(" ",SwingConstants.RIGHT); 435: } 436: 437: for (int i = 0; i < maxVote; i++) 438: { 439: // System.out.println("Initializing totLabel["+i+"]"); 440: voteArray[i] = '0'; 441: voteCount[i] = 0; 442: batLabel[i] = new JLabel("0",JLabel.RIGHT); 443: batLabel[i].setFont(defaultFont); 444: totLabel[i] = new JLabel("0",JLabel.RIGHT); 445: totLabel[i].setFont(defaultFont); 446: voteBox[i] = new JCheckBox(" "+voteName[i], false); 447: voteBox[i].setToolTipText("Check Box or type underlined # to select."); 448: voteBox[i].setFont(defaultFont); 449: tempInt = new Integer(i); 450: acString = tempInt.toString(); 451: voteBox[i].setActionCommand(acString); 452: voteBox[i].setMnemonic(voteName[i].charAt(1)); 453: KeyStroke aKey = KeyStroke.getKeyStroke(voteName[i].charAt(1)); 454: voteBox[i].addItemListener(il); 455: voteBox[i].registerKeyboardAction(al,acString,aKey, 456: JComponent.WHEN_IN_FOCUSED_WINDOW); 457: } 458: 459: 460: // System.out.println("Constants set "); 461: // now can continue with input file 462: String vChar; 463: // input.setName(inputFileName); // don't need as set above! 464: while (0 <= input.getNext()) 465: { 466: inputLine = input.getLine(); 467: // System.out.println("Input VoteString: "+inputLine); 468: if (inputLine.length() < (maxVote*2)) 469: { 470: sysout.display("Skipping line of length="+inputLine.length()); 471: } 472: else 473: { 474: newVote (); 475: for (int v=0; v < maxVote; v++) 476: { 477: vChar = inputLine.substring(v*2,v*2+1); 478: // System.out.println("v="+v+"v*2="+(v*2)+"=="+vChar); 479: if (vChar.equals("1")) 480: { 481: voteCount[v]++; 482: batchVote[b][v]++; 483: } 484: } 485: voteBallot++; 486: batchBallot[b]++; 487: writeBallot(inputLine); 488: } 489: 490: } 491: // System.out.println("After input votes."); 492: batSumLabel.setText(" "+ batchBallot[b]); 493: totSumLabel.setText("Total: " + voteBallot); 494: for (int v=0; v < maxVote; v++) 495: { 496: batLabel[v].setText(" "+batchVote[b][v]); 497: totLabel[v].setText(" "+voteCount[v]); 498: } 499: 500: 501: // Throw everything together. 502: frame.setJMenuBar(new VoteMenuListener()); 503: Container c = frame.getContentPane(); 504: 505: c.setLayout(new GridLayout(maxVote+maxRace+2,3)); // items added left to right 506: 507: batHead.setText("Batch # "+(b+1)); 508: batHead.setFont(defaultFont); 509: totHead.setFont(defaultFont); 510: c.add(dotLabel1); 511: c.add(batHead); 512: c.add(totHead); 513: 514: ir = -1; 515: for (int i = 0; i < maxVote; i++) 516: { 517: if (voteRace[i] != ir) 518: { 519: ir = voteRace[i]; 520: c.add(raceLabel1[ir]); 521: c.add(raceLabel2[ir]); 522: c.add(raceLabel3[ir]); 523: } 524: c.add(voteBox[i]); 525: c.add(batLabel[i]); 526: c.add(totLabel[i]); 527: 528: } 529: JButton voteButton = (new JButton("Vote")); 530: voteButton.setMnemonic('V'); 531: voteButton.setToolTipText("Press Vote button (or enter) to cast one ballot."); 532: voteButton.addActionListener(new ActionListener() 533: { 534: public void actionPerformed(ActionEvent ev) 535: { 536: String voteString = ""; 537: newVote(); 538: if (batchBallot[b] == 0) 539: { 540: batHead.setText("Batch # "+(b+1)); 541: for (int i = 0; i < maxVote; i++) 542: batLabel[i].setText(" "+batchVote[b][i]); 543: // reset labels to zero if batch changes 544: } 545: 546: for (int i = 0; i < maxVote; i++) 547: { 548: voteString += voteArray[i]+","; 549: if (voteArray[i] == '1') 550: { 551: // voteArray[i] = '0'; this will be done by itemListener 552: voteBox[i].setSelected(false); 553: batchVote[b][i]++; 554: voteCount[i]++; 555: batLabel[i].setText(" "+batchVote[b][i]); 556: totLabel[i].setText(" "+voteCount[i]); 557: } 558: } 559: voteBallot++; 560: batchBallot[b]++; 561: batSumLabel.setText(" "+ batchBallot[b]); 562: totSumLabel.setText("Total: " + voteBallot); 563: voteString += u.padZero(voteBallot,5); 564: for (int i = 0; i < maxRace; i++) raceVotes[i] = 0; 565: 566: System.out.println("Vote Button Pressed, Votes=" + voteString); 567: writeBallot(voteString); 568: if (batchBallot[b] == batchSize) 569: JOptionPane.showMessageDialog(frame, 570: "Please generate This Batch Report now. \n"+ 571: "Thanks, and Have a Nice Day!"); 572: } 573: }); // yes that is } bracket and ) parenthesis. 574: 575: c.add(voteButton); 576: batSumLabel.setFont(defaultFont); 577: totSumLabel.setFont(defaultFont); 578: c.add(batSumLabel); 579: c.add(totSumLabel); 580: 581: // System.out.println("Frame display "); 582: 583: frame.pack(); // sets size to just as big as it needs to be 584: // frame.setSize(600,600); // or could set to specific size 585: 586: frame.setVisible(true); 587: voteButton.grabFocus(); // must be done after screen is visible 588: // try grabFocus vs. requestFocus 589: } 590: 591: public void newVote() 592: { 593: // sysout.display("newVote: b="+b+" batchBallot[b]="+batchBallot[b]+"batchSize="+batchSize); 594: if (batchBallot[b] == batchSize) 595: { 596: b++; 597: batchBallot[b] = 0; 598: for (int i=0; i < maxVote; i++) batchVote[b][i] = 0; 599: } 600: } 601: 602: public void writeBallot(String voteString) 603: { 604: output.setLine(voteString); 605: } 606: 607: public void doAllReport() 608: { 609: sysout.display("doAllReport called, Last Batch # "+(b+1)); 610: for (int i=0; i < maxVote; i++) cummCount[i] = 0; 611: cummBallot = 0; 612: lineCount = 999; // force report to page break 613: for (int bt=0; bt <= b; bt++) 614: { 615: //sysout.display("lineCount="+lineCount+"/"+printLPP); 616: if ((lineCount+maxVote+4) > printLPP) 617: { 618: printOneLine("1JsrVote "+voteTitle); 619: printOneLine(" "+today+" All Batches Report"); 620: lineCount = 4; 621: } 622: lineCount++; // extra bump for double space 623: printOneLine("0Race & Candidate Batch #"+u.padLeft(bt+1, 3)+" All Batches"); 624: for (int i=0; i < maxVote; i++) 625: { 626: if ((i == 0) || (voteRace[i] != voteRace[i-1])) 627: printOneLine(" "+raceName[voteRace[i]]); 628: cummCount[i] += batchVote[bt][i]; 629: printOneLine(" "+u.padRight(voteName[i],25) 630: +u.padLeft(batchVote[bt][i],10) 631: +u.padLeft(cummCount[i],12)); 632: } 633: cummBallot += batchBallot[bt]; 634: printOneLine(" Totals " +u.padLeft(batchBallot[bt],10) 635: +u.padLeft(cummBallot,12)); 636: } 637: report.close(); 638: if (printOn) print1.main(print1Parm); 639: } 640: 641: public void doThisReport() 642: { 643: System.out.println("doThisReport called, Batch # "+(b+1)); 644: lineCount = 999; // force report to page break 645: if (lineCount > printLPP) 646: { 647: printOneLine("1JsrVote "+voteTitle); 648: printOneLine(" "+today+" Current Batch Report"); 649: lineCount = 4; 650: } 651: printOneLine("0Race & Candidate Batch #"+u.padLeft(b+1, 3)+" All Batches"); 652: for (int i=0; i < maxVote; i++) 653: { 654: if ((i == 0) || (voteRace[i] != voteRace[i-1])) 655: printOneLine(" "+raceName[voteRace[i]]); 656: printOneLine(" "+u.padRight(voteName[i],25) 657: +u.padLeft(batchVote[b][i],10) 658: +u.padLeft(voteCount[i],12)); 659: } 660: printOneLine(" Totals " +u.padLeft(batchBallot[b],10) 661: +u.padLeft(voteBallot,12)); 662: report.close(); 663: if (printOn) print1.main(print1Parm); 664: } 665: 666: public void doPlotVotes() 667: { 668: 669: sysout.display("doPlotVotes called, Batch # "+(b+1)); 670: lineCount = 999; // force report to page break 671: if (lineCount > printLPP) 672: { 673: printOneLine("1JsrVote "+voteTitle); 674: printOneLine(" "+today+" Plot Votes"); 675: lineCount = 4; 676: } 677: printOneLine("0# Ballots Cast: "+u.padLeft(voteBallot,12)); 678: int plotSpread = 80 / (b+1); 679: //sysout.display("alloc plotChar[50]["+plotSpread*(b+1)+"]"); 680: char [][] plotChar = new char[50][plotSpread*(b+1)]; 681: for (int i=0; i < 50; i++) 682: for (int j=0; j < (plotSpread*(b+1)); j++) 683: plotChar[i][j] = ' '; 684: //sysout.display("init cummCount"); 685: for (int i=0; i < maxVote; i++) cummCount[i] = 0; 686: lineValue = new int[maxVote][b+1]; // make size = this batch not max... 687: for (int bt=0; bt <= b; bt++) 688: { 689: for (int i=0; i < maxVote; i++) 690: { 691: //set lineValue array to be passed to JsrLinePlot 692: if (bt == 0) lineValue[i][bt] = batchVote[bt][i]; 693: else lineValue[i][bt] = batchVote[bt][i] + lineValue[i][bt-1]; 694: //sysout.display("CummCount set="+ cummCount[i] +"+="+ batchVote[bt][i] ); 695: cummCount[i] += batchVote[bt][i]; 696: int p = (cummCount[i] * 50) / voteBallot; 697: //sysout.display("bt="+bt+" * X="+(plotSpread*bt)+" p="+p+ 698: // " Vote="+cummCount[i]+" Who: "+voteName[i]); 699: if (plotChar[p][plotSpread*bt] == ' ') 700: plotChar[p][plotSpread*bt] = voteName[i].charAt(1); 701: else 702: plotChar[p][plotSpread*bt] = '*'; 703: //sysout.display("after set plotChar..."); 704: } 705: } 706: for (int p=49; p >=0; p--) 707: { 708: String printString = new String(" |"); 709: if (p == 49) printString = u.padLeft(voteBallot,10) + "+"; 710: if (p == 36) printString = u.padLeft(voteBallot*3/4,10) + "+"; 711: if (p == 24) printString = u.padLeft(voteBallot/2,10) + "+"; 712: if (p == 11) printString = u.padLeft(voteBallot/4,10) + "+"; 713: for (int bt=0; bt<=(plotSpread*b); bt++) printString += plotChar[p][bt]; 714: printOneLine(" "+printString); 715: } 716: printOneLine(" 0+---------+---------+---------+---------+"+ 717: "---------+---------+---------+---------+"); 718: printOneLine(" Batches->"); 719: report.close(); 720: if (printOn) print1.main(print1Parm); 721: 722: // now call Plot Path program. 723: linePlot.drawLinePlot(today+" Ballots Cast: "+ 724: u.padLeft(voteBallot,3), 725: lineLabel, lineValue, lineSelect); 726: // see if can invoke plot 727: 728: } 729: 730: 731: public void printOneLine(String oneLine) 732: { 733: report.setLine(oneLine.substring(0,1)+" "+oneLine.substring(1)); 734: lineCount++; 735: } 736: 737: 738: 739: } 740: // end of JsrVote.java program