Project3.java public class Project3 { static DateGUI myGUI; public static void m
ID: 3578019 • Letter: P
Question
Project3.java
public class Project3 {
static DateGUI myGUI;
public static void main(String[] args) {
myGUI = new DateGUI(); //once myGUI is created, all the work is done following it
}
}
DateGUI.java
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.TextArea;
import javax.swing.*;
public class DateGUI extends JFrame {
Container cPane; //create container 'cPane'
JMenuBar menuBar;
static TextArea sorted; //create two text areas for sorted and original lists
static TextArea unsorted;
public DateGUI() {
setTitle("PROJECT 3");
setSize(300,300);
setLocation(400, 200);
createFileMenu();
createLists();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
/**
* createLists: create text areas for storing dates
* @return void
*/
public void createLists() {
setLayout(new GridLayout(1, 2));
sorted = new TextArea(); sorted.setEditable(false); sorted.setBackground(Color.PINK); //set text areas and options
unsorted = new TextArea(); unsorted.setEditable(false); unsorted.setBackground(Color.LIGHT_GRAY);
cPane = getContentPane(); //initialize content pane for usage
cPane.add(unsorted); //add to content pane the text area 'unsorted'
cPane.add(sorted); //add to content pane the text area 'sorted'
}
/**
* print: appends dates to text areas created from createLists()
* @return void
*/
public static void print (DateList x, DateList y, int z) { //print method created to take in two date lists and append them to text areas
unsorted.append("ORIGINAL LIST: "); //append initial line as titles for unsorted list
sorted.append("SORTED LIST: "); //append initial line for sorted list
sorted.append(x.toString()); //toString() because append only accepts string type
unsorted.append(y.toString());
sorted.append(" total valid dates: "+String.valueOf(z)); //output total number of valid dates in lists
unsorted.append(" total valid dates: "+String.valueOf(z));
}
private void createFileMenu() {
menuBar = new JMenuBar(); //create new menu bar
JMenu fileMenu = new JMenu("FILE"); //create new file tree called "FILE"
FileMenuHandler fmh = new FileMenuHandler(this); //link to filemenuhandler class
JMenuItem item; //initialize 'item'
item = new JMenuItem("OPEN"); //create new item for menu "OPEN"
item.addActionListener(fmh); //add action listener to OPEN
fileMenu.add(item); //attach "OPEN" to fileMenu "FILE"
fileMenu.addSeparator(); // add a horizontal separator line
item = new JMenuItem("QUIT"); // Quit
item.addActionListener(fmh); //
fileMenu.add(item); //
setJMenuBar(menuBar); //set and attach filemenu to menu bar*
menuBar.add(fileMenu);
}
}
FileMenuHandler.java
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileMenuHandler implements ActionListener {
JFrame jframe;
public static TextFileInput inputFile;
public static String line="";
public static StringTokenizer myTokens;
public static boolean runOnce;
public FileMenuHandler(JFrame jf) {
jframe = jf;
}
public void actionPerformed(ActionEvent event) {//listen to user actions
String menuName = event.getActionCommand();//retrivew user action and set as 'menuName'
if (menuName.equals("OPEN") && runOnce==false) { //if user action = OPEN, proceed to open file chooser
JFileChooser myFile = new JFileChooser(); //create file chooser
int key = myFile.showOpenDialog(null);
myFile.setFileSelectionMode(JFileChooser.FILES_ONLY); //allow files to be selected only
if (key == JFileChooser.APPROVE_OPTION) { //if file is chosen, proceed to process file by using TextFileInput and tokenizer
JOptionPane.showMessageDialog(null, "Opening File...");
File f = myFile.getSelectedFile(); //save selected file to 'f'
inputFile = new TextFileInput(f.getAbsolutePath()); //feed absolute path of 'f' to textfileinput
magic(); //start the magic
}
}
else if (menuName.equals("QUIT")) { //if user action = QUIT, exit
JOptionPane.showMessageDialog(null, "Good Bye!");
System.exit(0);
}
}
/**
* magic: responsible for processing text file that the user chooses
* tokenizes each line while working with textfileinput
* implements try,catch blocks, prints to GUI
* @return void
*/
public void magic() {
UnsortedDateList unsorted = new UnsortedDateList(); //create unsorted and sorted date list OBJECTS!
SortedDateList sorted = new SortedDateList(); //DateList object with the name 'sorted'
while(line!=null) {
myTokens = new StringTokenizer(line,","); //set myTokens as the current 'line' tokenized and begin working on the line
while ( myTokens.hasMoreTokens() ) { //while line read has MORE TOKENS, check token validity and save to ssnList IF VALID!
String tokenHolder = myTokens.nextToken().trim(); //tokenHolder is holding the value because using .nextToken always forces next token up one unit!!!***
try {
Date212 dataEntry = new Date212(tokenHolder); //create a new object of type Date212 'dataEntry' that takes in the value held by tokenHolder
unsorted.add(dataEntry); //append dataEntry to 'unsorted' object DateList
sorted.add(dataEntry); //insert dataEntry to 'sorted' object DateList
}
catch (NumberFormatException nfe) {
System.out.println("Error in Entry: " + tokenHolder + " - not a number ");
}
catch (IllegalDate212Exception e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println("Entry: " + tokenHolder + " - not a valid date");
}
}
line = inputFile.readLine(); //move to next line in file and READ it in, store in 'line' for processing in next loop
}
DateGUI.print(sorted,unsorted,sorted.getLength()); //file is finished reading, call print from DateGUI
runOnce=true; //set true so the user can't press open file again
}
}
TextFileInput.java
// TextFileInput.java
// Copyright (c) 2000, 2005 Dorothy L. Nixon. All rights reserved.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
/**
* Simplified buffered character input
* stream from an input text file.
* Manages an input text file,
* handling all IOExceptions by generating
* RuntimeExcpetions (run-time error
* messages).
*
* If the text file cannot be created,
* a RuntimeException is thrown,
* which by default results an an
* error message being printed to
* the standard error stream.
*
* @author D. Nixon
*/
public class TextFileInput {
/** Name of text file */
private String filename;
/** Buffered character stream from file */
private BufferedReader br;
/** Count of lines read so far. */
private int lineCount = 0;
/**
* Creates a buffered character input
* strea, for the specified text file.
*
* @param filename the input text file.
* @exception RuntimeException if an
* IOException is thrown when
* attempting to open the file.
*/
public TextFileInput(String filename)
{
this.filename = filename;
try {
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));
} catch ( IOException ioe ) {
throw new RuntimeException(ioe);
} // catch
} // constructor
/**
* Closes this character input stream.
* No more characters can be read from
* this TextFileInput once it is closed.
* @exception NullPointerException if
* the file is already closed.
* @exception RuntimeException if an
* IOException is thrown when
* closing the file.
*/
public void close()
{
try {
br.close();
br = null;
} catch ( NullPointerException npe ) {
throw new NullPointerException(
filename + "already closed.");
} catch ( IOException ioe ) {
throw new RuntimeException(ioe);
} // catch
} // method close
/**
* Reads a line of text from the file and
* positions cursor at 0 for the next line.
* Reads from the current cursor position
* to end of line.
* Implementation does not invoke read.
*
* @return the line of text, with
* end-of-line marker deleted.
* @exception RuntimeException if an
* IOException is thrown when
* attempting to read from the file.
*/
public String readLine()
{
return readLineOriginal();
} // method readLine()
/**
* Returns a count of lines
* read from the file so far.
*/
public int getLineCount() { return lineCount; }
/**
* Tests whether the specified character is equal,
* ignoring case, to one of the specified options.
*
* @param toBeChecked the character to be tested.
* @param options a set of characters
* @return true if <code>toBeChecked</code> is
* equal, ignoring case, to one of the
* <code>options</code>, false otherwise.
*/
public static boolean isOneOf(char toBeChecked,
char[] options)
{
boolean>
for ( int i = 0; i < options.length && !oneOf; i++ )
if ( Character.toUpperCase(toBeChecked)
== Character.toUpperCase(options[i]) )
oneOf = true;
return oneOf;
} // method isOneOf(char, char[])
/**
* Tests whether the specified string is one of the
* specified options. Checks whether the string
* contains the same sequence of characters (ignoring
* case) as one of the specified options.
*
* @param toBeChecked the String to be tested
* @param options a set of Strings
* @return true if <code>toBeChecked</code>
* contains the same sequence of
* characters, ignoring case, as one of the
* <code>options</code>, false otherwise.
*/
public static boolean isOneOf(String toBeChecked,
String[] options)
{
boolean>
for ( int i = 0; i < options.length && !oneOf; i++ )
if ( toBeChecked.equalsIgnoreCase(options[i]) )
oneOf = true;
return oneOf;
} // method isOneOf(String, String[])
/**
* Reads a line from the text file and ensures that
* it matches one of a specified set of options.
*
* @param options array of permitted replies
*
* @return the line of text, if it contains the same
* sequence of characters (ignoring case for
* letters) as one of the specified options,
* null otherwise.
* @exception RuntimeException if the line of text
* does not match any of the specified options,
* or if an IOException is thrown when reading
* from the file.
* @exception NullPointerException if no options are
* provided, or if the end of the file has been
* reached.
*/
public String readSelection(String[] options)
{
if ( options == null || options.length == 0 )
throw new NullPointerException(
"No options provided for "
+ " selection to be read in file "
+ filename + ", line "
+ (lineCount + 1) + ".");
String answer = readLine();
if ( answer == null )
throw new NullPointerException(
"End of file "
+ filename + "has been reached.");
if ( !TextFileInput.isOneOf(answer, options) ) {
String optionString = options[0];
for ( int i = 1; i < options.length; i++ )
optionString += ", " + options[i];
throw new RuntimeException("File " + filename
+ ", line " + lineCount
+ ": "" + answer
+ "" not one of "
+ optionString + ".");
} // if
return answer;
} // method readSelection
/**
* Reads a line from the text file and ensures that
* it matches, ignoring case, one of "Y", "N", "yes",
* "no", "1", "0", "T", "F", "true", or "false".
* There must be no additional characters on the line.
*
* @return <code>true</code> if the line matches
* "Y", "yes", "1" "T", or "true".
* <code>false</code> if the line matches
* "N", "no", "0", "F", or "false".
* @exception RuntimeException if the line of text
* does not match one of "Y", "N", "yes",
* "no", "1", "0", "T", "F", "true", or "false",
* or if an IOException is thrown when reading
* from the file.
* @exception NullPointerException if the end of the
* file has been reached.
*/
public boolean readBooleanSelection()
{
String[] options = {"Y", "N", "yes", "no", "1", "0",
"T", "F", "true", "false"};
String answer = readSelection(options);
return isOneOf(answer,
new String[] {"Y", "yes", "1", "T", "true"} );
} // method askUserYesNo
/**
* Reads a line of text from the file and
* increments line count. (This method
* is called by public readLine and is
* final to facilitate avoidance of side
* effects when public readLine is overridden.)
*
* @return the line of text, with
* end-of-line marker deleted.
* @exception RuntimeException if an
* IOException is thrown when
* attempting to read from the file.
*/
protected final String readLineOriginal()
{
try {
if ( br == null )
throw new RuntimeException(
"Cannot read from closed file "
+ filename + ".");
String line = br.readLine();
if ( line != null )
lineCount++;
return line;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} // catch
} // method readLineOriginal
} // class TextFileInput
DateList.java
public abstract class DateList {
DateNode first = new DateNode(null); /** First node in linked list - dummy node */
DateNode last = first; /** Last node in linked list */
int length = 0; /** Number of data items in the list. */
public int getLength() {
return length; //return length of datelist
}
public String toString() { //this is required or else only node addresses will be printed out, basically turns nodes in to strings
DateNode p = first.next; //set 'p' as second
String returnString = ""; //create a string
while (p != null) { //while 'p' has not become an empty node we continue looping
returnString += p.data + " "; //return each nodes data as strings in a new line
p = p.next; //set 'p' to 'p.next' to check next node in list... remember only until p becomes null, we stop
}
return returnString;
}
}
DateNode.java
public class DateNode{
protected Date212 data;
protected DateNode next;
public DateNode (Date212 d) { // constructor for incoming node creation
this.data = d;
this.next = null;
}
public DateNode() {
this.data = null;
this.next = null;
} // constructor for dummy
}
Date212.java
public class Date212 implements Comparable<Date212> { //note the implements Comparable thingy here
private int year;
private int month;
private int day;
private int date;
/**
* toString: necessary or else date nodes will print addresses instead of string values
* @return String converts month,day,year ints
*/
public String toString() { /** convert months and days that are less than 10 so that there is a "0" in front of them, IE: 10/09/1991 **/
String m=Integer.toString(month); //store string value of month to 'm'
String d=Integer.toString(day); //store string value of day to 'd'
if(month<10) m = "0" + month; //if month is less than 10, combine 0+month
if(day<10) d = "0" + day; //same, note *** m and d are only touched if any of these two conditions are true ***
return (m+"/"+d+"/"+year); //we can always return m and d because the initial values given to m and d are the original, untouched month and day
}
/**
* isValidDate: used to verify dates and check boundaries of validity
* if invalid detected, throw new IllegalDate212Exceptions
* @void
*/
public static void isValidDate(String s) {
//check the length of string
if (s.length() != 8) throw new IllegalDate212Exception ("Error in Entry: " + s + " - not 8 digits");
int yearCheck = Integer.parseInt(s.substring(0, 4));
int monthCheck = Integer.parseInt(s.substring(4, 6));
int dayCheck = Integer.parseInt(s.substring(6, 8));
if (yearCheck >= 2015 || yearCheck <= 0) throw new IllegalDate212Exception ("Error in Entry: " + s + " - year is out of range");
if (monthCheck >= 12 || monthCheck <= 0) throw new IllegalDate212Exception ("Error in Entry: " + s + " - month is out of range");
if (monthCheck == 1 || monthCheck == 3 || monthCheck == 5 || monthCheck == 7 || monthCheck == 8 || monthCheck == 10 || monthCheck == 12) {
if (dayCheck >= 31 || dayCheck <= 0) throw new IllegalDate212Exception ("Error in Entry: " + s + " - day is out of range");
}
if (monthCheck == 4 || monthCheck == 6 || monthCheck == 9 || monthCheck == 11) {
if (dayCheck >= 30 || dayCheck <= 0) throw new IllegalDate212Exception ("Error in Entry: " + s + " - day is out of range");
}
if (monthCheck == 2) {
if (dayCheck >= 28 || dayCheck <= 0) throw new IllegalDate212Exception ("Error in Entry: " + s + " - day is out of range");
}
}
public Date212(String d) {
isValidDate(d); //check if incoming date 'd' is valid with above method
//convert and split string to Year, Month, Day
year = Integer.parseInt(d.substring(0, 4));
month = Integer.parseInt(d.substring(4, 6));
day = Integer.parseInt(d.substring(6, 8));
}
/**
* compareTo: used to compare values of current date node with incoming date node
* first they are converted to strings and then compared again with built in string compareTo()
* @return int 1,-1,0 depending on comparison result
*/
public int compareTo(Date212 x) { //simple compare to after converting incoming & initial Date212 objects 'x' to strings
return ((year*10000) + (month*100) + day) - ((x.year*10000) + (x.month*100) + (x.day));
}
}
IllegalDate212Exception.java
public class IllegalDate212Exception extends IllegalArgumentException {
public IllegalDate212Exception(String msg) {
super(msg);
}
}
UnsortedDateList.java
public class UnsortedDateList extends DateList {
public void add (Date212 s) { //append method to attach items to end of linked list
DateNode n = new DateNode(s); //create new node 'n' with data from 's'
last.next = n; //point the PREVIOUS last node on the linked list to new node 'n'
last = n; //the idea behind 'append' is that we attach a node to the end of the list, so 'n' becomes the new last node
length++;
}
}
SortedDateList.java
public class SortedDateList extends DateList {
/**
* insert method, sorts the dates by checking all relevant neighbors against conditions
* @return void
*/
public void add(Date212 s) {
DateNode pointA=first; //make a point 'a' and abuse it to track our position
DateNode pointB=first.next; //and point 'b' which is after 'a'
DateNode n = new DateNode(s); //make new node 'n' with the incoming data from Date212 's'
while (pointA.next!=null) { //while ref point A.next is not null
pointB=pointA.next; //set point B to follow A
if(pointB.data.compareTo(s)>0) break; //if incoming data 's' is greater than b, break from this loop!
pointA=pointA.next; //otherwise, move point A one position
}
if (pointA.next ==null) { //list is empty, append incoming data
last.next = n;
last = n;
length++;
}
else { //list is not empty, insert incoming data 'n' in between A and B
pointA.next=n;
n.next=pointB;
length++;
}
}
}
All of above is given java file.
The question is use a TreeMap to sort the dates that are to be displayed, as usual, in the right column of the GridLayout. All the code you need is in the PowerPoint on TreeMaps. You will need to create a Comparator for the class Date212.
Submitting the Project.
You should now have at least the following files to submit for this project:
Explanation / Answer
Treemap class stores key- value pairs. So you need to store the dates as a key value pair. So the code will be.
=============================
class sortdates{
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.