SlideShare a Scribd company logo
1 of 11
Download to read offline
City GUI
Write a Java GUI program which reads data about US cities. The data file is different, but is in
the same format as in Lab #01. The GUI provides a combo box with the cities in the data file. As
cities are selected in the combo box, information about the city is displayed.
Requirements
1. The program must have a graphical user interface similar to the one on the bottom of the
Requirements section. It must have a text field, a button, a combo box, and labels.
2. One or more layout managers must be used. This example was created using a border layout.
The east and west panels each used a grid layout in addition.
3. A message must be displayed in the GUI after the data has been successfully read. A message
should also be displayed if the file is not found. The program should not exit in that case, but
allow the user to enter a different file name.
4. The combo box must be populated by the names of the cities in the data file in alphabetical
order. Note that this means the GUI starts with an empty combo box. Items are added to it as or
after the data file is read.
5. The program must provide an ActionListener for the Read button. It must also provide either
an ActionListener or an ItemListener for the combo box, which displays the state, zip code, and
time zone for that city.
6. The information for each city must be stored in its own object. Another object must be used to
manage the collection of cities. This is similar to Lab #01. For this assignment you may assume
that there will be no more than 100 cities.
7. The time zone should be displayed as the correct abbreviation for that city’s time zone in July.
Here are the abbreviations. If the city observes daylight savings time, the S should be changed to
a D. Note that some cities in the data file do not observe daylight savings time.
Hours relative to GMT -4 -5 -6 -7 -8 -9 -10
Standard Time Abr. AST EST CST MST PST AKST HST
I have attached an executable .jar file to the assignment that you can run to see how this program
should work. Copy it to your computer. Copy the data file into the same directory as the .jar file.
Suggestions
1. Create class diagrams first. This will help you think through and organize your program. There
are many ways to do this. Start with the class diagrams from Lab #01. Both classes will require
some additions.
2. Create the GUI and handle the IO in a separate class which extends JFrame. The main method
can be included in this class.
3. Don’t worry about making your implementation efficient or using wonderful abstract data
types (ADTs). You will be required to do that soon enough.
4. This program will take you several days to complete. Break it down into smaller tasks. This is
the order I used, yours may be different.
*Modify the class diagrams from Lab #01 to include new requirements that you identify now.
You can add additional functionality later as you discover the need.
*Implement those changes in the classes.
* Create a GUI class. Implement a non-functional GUI that just displays a window like that
above.
* Implement an action listener for the Read button. You can use much of the code from the Lab
#01 main method to read the data and create objects.
* Sort the list of cities alphabetically. You can do this as cities are added or after they have all
been added.
* Populate the combo box with the city names.
* Convert the time zone and daylight savings time information into the abbreviation strings. I did
this in a getTimeZone() method added to the City class.
* Implement the combo box selection listener. I used an action listener. It can also be done with
an item listener.
* Our textbook has many good examples, but does not have all of the information you will need.
Simple Google searches for terms like Java adding items to combo box will provide all the
information you need.
* Don’t hesitate to ask your classmates, your instructor, or Java programmers you know for help.
Upload
All of the Java source files required to build your program. You only need to upload the source
files in the Blackboard assignment. I don’t want the executable, byte files, or project files.
Here are the files:
Lab 1 source files:
import java.io.File;
import java.io.*;
import java.util.*;
public class Main
{
/**
* this is the main class
* @return main
* */
public static void main(String[] args)throws IOException
{
/**
* this is main() class in which getters are performed and displays info
* @return City()
*/
CityGroup cg=new CityGroup();
Scanner fileScan=new Scanner(new File("CityData1.csv"));
Scanner deLimit=null;
String fileLine=fileScan.nextLine();
while(fileScan.hasNext()==true)
{
fileLine=fileScan.nextLine();
deLimit=new Scanner(fileLine);
deLimit.useDelimiter(",");
while(deLimit.hasNext()==true)
{
int zip=deLimit.nextInt();
String cName=deLimit.next();
String state=deLimit.next();
double lat=deLimit.nextDouble();
double lon=deLimit.nextDouble();
int zone=deLimit.nextInt();
boolean yesDay=false;
String daylightStr=deLimit.next();
if(daylightStr.charAt(0)=='1')
yesDay=true;
City temp=new City(zip,cName,state,lat,lon,zone,yesDay);
cg.addCity(temp);
}
}
System.out.println("Northernmost city: " +cg.findNorthMost());
}
}
public class CityGroup
{
/**
* this is main citygroup class
* @return CityGroup
*/
City[] cityArray=new City[100];
int numCities;
public CityGroup()
{
/**
* this sets cities to 0;
* @return numCities
*/
numCities=0;
}
public void addCity(City newCity)
{
/**
* this is returns the cityarray after its added
* @return cityArray[]
*/
cityArray[numCities]=newCity;
numCities++;
}
City findNorthMost()
{
City noa =cityArray[0];
for(int counter=0;counter {
if(cityArray[counter].compareTo(noa)==1)
noa=cityArray[counter];
}
return noa;
}
}
public class City
{
/**
* this is main city class
* @return City
*/
int zipcode;
String cityName;
String state;
double latitude;
double longitude;
int timezone;
boolean yesDaylight;
public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight)
{
/**
* this is constructor for City
* @return City()
*/
zipcode = zip;
cityName = cName;
state = st;
latitude = lat;
longitude = lon;
timezone = zone;
yesDaylight = daylight;
}
public String toString()
{
/**
* this is the toString class
* @return cityName + "," state;
*/
return cityName + ", " + state;
}
public int compareTo (City otherCity)
{
/**
* this is compareTo class to compare
* @return compareTo;
*/
if (otherCity.latitude == latitude)
return 0;
else if (latitude > otherCity.latitude)
return 1;
else
return -1;
}
}
GUI that i have already:
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif", Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, "City information", 200, 75);
}
protected void paintHorizontallyCenteredText(Graphics2D g2,
String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width / 2, baselineY);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(450, 350);
f.setVisible(true);
}
}
CityData 2: 3 Cities O O X City Information CityData2.csv J Read Input File Select City State:
ZipCode: Time Zone:
Solution
import java.io.File;
import java.io.*;
import java.util.*;
public static void main(String[] args)throws IOException
{
/**
this is main() class in which the ‘new city’ data is taken and displays info
@return City()
**/
CityGroup cg=new CityGroup();
Scanner fileScan=new Scanner(new File("CityData1.csv"));
Scanner deLimit=null;
String fileLine=fileScan.nextLine();
while(fileScan.hasNext()==true)
{
fileLine=fileScan.nextLine();
deLimit=new Scanner(fileLine);
deLimit.useDelimiter(",");
while(deLimit.hasNext()==true)
{
int zip=deLimit.nextInt();
String cName=deLimit.next();
String state=deLimit.next();
double lat=deLimit.nextDouble();
double lon=deLimit.nextDouble();
int zone=deLimit.nextInt();
boolean yesDay=false;
String daylightStr=deLimit.next();
if(daylightStr.charAt(0)=='1')
yesDay=true;
City temp=new City(zip,cName,state,lat,lon,zone,yesDay);
cg.addCity(temp);
}
}
System.out.println("Northernmost city: " +cg.findNorthMost());
}
}
public class CityGroup
{
/**
this is main citygroup class
@return CityGroup
**/
City[] cityArray=new City[100];
int numCities;
public CityGroup()
{
/**
this sets cities to 0;
@return numCities
**/
numCities=0;
}
public void addCity(City newCity)
{
/**
this returns the value for ‘cityarray’ after its added
@return cityArray[]
**/
cityArray[numCities]=newCity;
numCities++;
}
City findNorthMost()
{
City noa =cityArray[0];
for(int counter=0;counter {
if(cityArray[counter].compareTo(noa)==1)
noa=cityArray[counter];
}
return noa;
}
}
public class City
{
/**
this is main city class
@return City
**/
int zipcode;
String cityName;
String state;
double latitude;
double longitude;
int timezone;
boolean yesDaylight;
public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight)
{
/**
this is constructor for the Class City
@return City()
**/
zipcode = zip;
cityName = cName;
state = st;
latitude = lat;
longitude = lon;
timezone = zone;
yesDaylight = daylight;
}
public String toString()
{
/**
this is the toString class
@return cityName + "," state;
**/
return cityName + ", " + state;
}
public int compareTo (City otherCity)
{
/**
this is compareTo class to compare
@return compareTo;
**/
if (otherCity.latitude == latitude)
return 0;
else if (latitude > otherCity.latitude)
return 1;
else
return -1;
}
}
GUI that i have already:
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif", Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, "City information", 200, 75);
}
protected void paintHorizontallyCenteredText(Graphics2D g2,
String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width / 2, baselineY);
}
**/ main function initializing ‘Frame’ **/
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(450, 350);
f.setVisible(true);
}
}

More Related Content

Similar to City GUIWrite a Java GUI program which reads data about US cities..pdf

Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
Katie Gulley
 
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdfYour 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
abhijitmaskey
 
Question 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdfQuestion 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdf
anjandavid
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
honey725342
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 
Spatial Data Integrator - Software Presentation and Use Cases
Spatial Data Integrator - Software Presentation and Use CasesSpatial Data Integrator - Software Presentation and Use Cases
Spatial Data Integrator - Software Presentation and Use Cases
mathieuraj
 

Similar to City GUIWrite a Java GUI program which reads data about US cities..pdf (20)

System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
 
Introduction to F#
Introduction to F#Introduction to F#
Introduction to F#
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdfYour 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdf
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Question 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdfQuestion 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdf
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Gsoc proposal 2021 polaris
Gsoc proposal 2021 polarisGsoc proposal 2021 polaris
Gsoc proposal 2021 polaris
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Spatial Data Integrator - Software Presentation and Use Cases
Spatial Data Integrator - Software Presentation and Use CasesSpatial Data Integrator - Software Presentation and Use Cases
Spatial Data Integrator - Software Presentation and Use Cases
 
Functions
FunctionsFunctions
Functions
 
Python ppt
Python pptPython ppt
Python ppt
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Gsoc proposal
Gsoc proposalGsoc proposal
Gsoc proposal
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Rpg Pointers And User Space
Rpg Pointers And User SpaceRpg Pointers And User Space
Rpg Pointers And User Space
 

More from rushabhshah600

art F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdfart F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdf
rushabhshah600
 
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdfEcosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
rushabhshah600
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 
Distinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdfDistinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdf
rushabhshah600
 
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdfDifferentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
rushabhshah600
 
Briefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdfBriefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdf
rushabhshah600
 
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
Background  Angiosperms (flowering plants) are the largest Phylum in .pdfBackground  Angiosperms (flowering plants) are the largest Phylum in .pdf
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
rushabhshah600
 
Write a Pep8 Assembly program that reads in and stores two integers .pdf
Write a Pep8 Assembly program that reads in and stores two integers .pdfWrite a Pep8 Assembly program that reads in and stores two integers .pdf
Write a Pep8 Assembly program that reads in and stores two integers .pdf
rushabhshah600
 

More from rushabhshah600 (20)

Give an expression for the pattern inventory of 2-colorings of the ed.pdf
Give an expression for the pattern inventory of 2-colorings of the ed.pdfGive an expression for the pattern inventory of 2-colorings of the ed.pdf
Give an expression for the pattern inventory of 2-colorings of the ed.pdf
 
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdfFor the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
 
External respiration includes all of these processes EXCEPT _____. r.pdf
External respiration includes all of these processes EXCEPT _____.  r.pdfExternal respiration includes all of these processes EXCEPT _____.  r.pdf
External respiration includes all of these processes EXCEPT _____. r.pdf
 
art F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdfart F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdf
 
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdfEcosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
 
b) Analyze your network IP packets headers and contents.Solu.pdf
b) Analyze your network IP packets headers and contents.Solu.pdfb) Analyze your network IP packets headers and contents.Solu.pdf
b) Analyze your network IP packets headers and contents.Solu.pdf
 
A type A man is the son of a type O father and type A mother. If he .pdf
A type A man is the son of a type O father and type A mother. If he .pdfA type A man is the son of a type O father and type A mother. If he .pdf
A type A man is the son of a type O father and type A mother. If he .pdf
 
A One-Way Analysis of Variance is a way to test the equality of thre.pdf
A One-Way Analysis of Variance is a way to test the equality of thre.pdfA One-Way Analysis of Variance is a way to test the equality of thre.pdf
A One-Way Analysis of Variance is a way to test the equality of thre.pdf
 
5 000-0 SolutionEquity multiplier = Total Assets Equityor, .pdf
5 000-0 SolutionEquity multiplier = Total Assets  Equityor, .pdf5 000-0 SolutionEquity multiplier = Total Assets  Equityor, .pdf
5 000-0 SolutionEquity multiplier = Total Assets Equityor, .pdf
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
4 (4 points). How would you describe the difference in cell structur.pdf
4 (4 points). How would you describe the difference in cell structur.pdf4 (4 points). How would you describe the difference in cell structur.pdf
4 (4 points). How would you describe the difference in cell structur.pdf
 
Distinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdfDistinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdf
 
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdfDifferentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
 
Define induction and give an example of deductive reasoningSolu.pdf
Define induction and give an example of deductive reasoningSolu.pdfDefine induction and give an example of deductive reasoningSolu.pdf
Define induction and give an example of deductive reasoningSolu.pdf
 
A report says that the between-subjects factor of participants sal.pdf
A report says that the between-subjects factor of participants sal.pdfA report says that the between-subjects factor of participants sal.pdf
A report says that the between-subjects factor of participants sal.pdf
 
What is the role of sulfur chemoautotrophs in the sulfur cycle Deco.pdf
What is the role of sulfur chemoautotrophs in the sulfur cycle  Deco.pdfWhat is the role of sulfur chemoautotrophs in the sulfur cycle  Deco.pdf
What is the role of sulfur chemoautotrophs in the sulfur cycle Deco.pdf
 
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdfWhat is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
 
Briefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdfBriefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdf
 
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
Background  Angiosperms (flowering plants) are the largest Phylum in .pdfBackground  Angiosperms (flowering plants) are the largest Phylum in .pdf
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
 
Write a Pep8 Assembly program that reads in and stores two integers .pdf
Write a Pep8 Assembly program that reads in and stores two integers .pdfWrite a Pep8 Assembly program that reads in and stores two integers .pdf
Write a Pep8 Assembly program that reads in and stores two integers .pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

City GUIWrite a Java GUI program which reads data about US cities..pdf

  • 1. City GUI Write a Java GUI program which reads data about US cities. The data file is different, but is in the same format as in Lab #01. The GUI provides a combo box with the cities in the data file. As cities are selected in the combo box, information about the city is displayed. Requirements 1. The program must have a graphical user interface similar to the one on the bottom of the Requirements section. It must have a text field, a button, a combo box, and labels. 2. One or more layout managers must be used. This example was created using a border layout. The east and west panels each used a grid layout in addition. 3. A message must be displayed in the GUI after the data has been successfully read. A message should also be displayed if the file is not found. The program should not exit in that case, but allow the user to enter a different file name. 4. The combo box must be populated by the names of the cities in the data file in alphabetical order. Note that this means the GUI starts with an empty combo box. Items are added to it as or after the data file is read. 5. The program must provide an ActionListener for the Read button. It must also provide either an ActionListener or an ItemListener for the combo box, which displays the state, zip code, and time zone for that city. 6. The information for each city must be stored in its own object. Another object must be used to manage the collection of cities. This is similar to Lab #01. For this assignment you may assume that there will be no more than 100 cities. 7. The time zone should be displayed as the correct abbreviation for that city’s time zone in July. Here are the abbreviations. If the city observes daylight savings time, the S should be changed to a D. Note that some cities in the data file do not observe daylight savings time. Hours relative to GMT -4 -5 -6 -7 -8 -9 -10 Standard Time Abr. AST EST CST MST PST AKST HST I have attached an executable .jar file to the assignment that you can run to see how this program should work. Copy it to your computer. Copy the data file into the same directory as the .jar file. Suggestions 1. Create class diagrams first. This will help you think through and organize your program. There are many ways to do this. Start with the class diagrams from Lab #01. Both classes will require some additions. 2. Create the GUI and handle the IO in a separate class which extends JFrame. The main method can be included in this class. 3. Don’t worry about making your implementation efficient or using wonderful abstract data
  • 2. types (ADTs). You will be required to do that soon enough. 4. This program will take you several days to complete. Break it down into smaller tasks. This is the order I used, yours may be different. *Modify the class diagrams from Lab #01 to include new requirements that you identify now. You can add additional functionality later as you discover the need. *Implement those changes in the classes. * Create a GUI class. Implement a non-functional GUI that just displays a window like that above. * Implement an action listener for the Read button. You can use much of the code from the Lab #01 main method to read the data and create objects. * Sort the list of cities alphabetically. You can do this as cities are added or after they have all been added. * Populate the combo box with the city names. * Convert the time zone and daylight savings time information into the abbreviation strings. I did this in a getTimeZone() method added to the City class. * Implement the combo box selection listener. I used an action listener. It can also be done with an item listener. * Our textbook has many good examples, but does not have all of the information you will need. Simple Google searches for terms like Java adding items to combo box will provide all the information you need. * Don’t hesitate to ask your classmates, your instructor, or Java programmers you know for help. Upload All of the Java source files required to build your program. You only need to upload the source files in the Blackboard assignment. I don’t want the executable, byte files, or project files. Here are the files: Lab 1 source files: import java.io.File; import java.io.*; import java.util.*; public class Main { /** * this is the main class * @return main * */ public static void main(String[] args)throws IOException
  • 3. { /** * this is main() class in which getters are performed and displays info * @return City() */ CityGroup cg=new CityGroup(); Scanner fileScan=new Scanner(new File("CityData1.csv")); Scanner deLimit=null; String fileLine=fileScan.nextLine(); while(fileScan.hasNext()==true) { fileLine=fileScan.nextLine(); deLimit=new Scanner(fileLine); deLimit.useDelimiter(","); while(deLimit.hasNext()==true) { int zip=deLimit.nextInt(); String cName=deLimit.next(); String state=deLimit.next(); double lat=deLimit.nextDouble(); double lon=deLimit.nextDouble(); int zone=deLimit.nextInt(); boolean yesDay=false; String daylightStr=deLimit.next(); if(daylightStr.charAt(0)=='1') yesDay=true; City temp=new City(zip,cName,state,lat,lon,zone,yesDay); cg.addCity(temp); } } System.out.println("Northernmost city: " +cg.findNorthMost()); } } public class CityGroup { /**
  • 4. * this is main citygroup class * @return CityGroup */ City[] cityArray=new City[100]; int numCities; public CityGroup() { /** * this sets cities to 0; * @return numCities */ numCities=0; } public void addCity(City newCity) { /** * this is returns the cityarray after its added * @return cityArray[] */ cityArray[numCities]=newCity; numCities++; } City findNorthMost() { City noa =cityArray[0]; for(int counter=0;counter { if(cityArray[counter].compareTo(noa)==1) noa=cityArray[counter]; } return noa; } } public class City { /**
  • 5. * this is main city class * @return City */ int zipcode; String cityName; String state; double latitude; double longitude; int timezone; boolean yesDaylight; public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight) { /** * this is constructor for City * @return City() */ zipcode = zip; cityName = cName; state = st; latitude = lat; longitude = lon; timezone = zone; yesDaylight = daylight; } public String toString() { /** * this is the toString class * @return cityName + "," state; */ return cityName + ", " + state; } public int compareTo (City otherCity) { /**
  • 6. * this is compareTo class to compare * @return compareTo; */ if (otherCity.latitude == latitude) return 0; else if (latitude > otherCity.latitude) return 1; else return -1; } } GUI that i have already: import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(new Font("Serif", Font.PLAIN, 48)); paintHorizontallyCenteredText(g2, "City information", 200, 75); } protected void paintHorizontallyCenteredText(Graphics2D g2, String s, float centerX, float baselineY) { FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D bounds = g2.getFont().getStringBounds(s, frc); float width = (float) bounds.getWidth(); g2.drawString(s, centerX - width / 2, baselineY); } public static void main(String[] args) { JFrame f = new JFrame(); f.getContentPane().add(new Main()); f.setSize(450, 350);
  • 7. f.setVisible(true); } } CityData 2: 3 Cities O O X City Information CityData2.csv J Read Input File Select City State: ZipCode: Time Zone: Solution import java.io.File; import java.io.*; import java.util.*; public static void main(String[] args)throws IOException { /** this is main() class in which the ‘new city’ data is taken and displays info @return City() **/ CityGroup cg=new CityGroup(); Scanner fileScan=new Scanner(new File("CityData1.csv")); Scanner deLimit=null; String fileLine=fileScan.nextLine(); while(fileScan.hasNext()==true) { fileLine=fileScan.nextLine(); deLimit=new Scanner(fileLine); deLimit.useDelimiter(","); while(deLimit.hasNext()==true) { int zip=deLimit.nextInt(); String cName=deLimit.next(); String state=deLimit.next(); double lat=deLimit.nextDouble(); double lon=deLimit.nextDouble(); int zone=deLimit.nextInt(); boolean yesDay=false;
  • 8. String daylightStr=deLimit.next(); if(daylightStr.charAt(0)=='1') yesDay=true; City temp=new City(zip,cName,state,lat,lon,zone,yesDay); cg.addCity(temp); } } System.out.println("Northernmost city: " +cg.findNorthMost()); } } public class CityGroup { /** this is main citygroup class @return CityGroup **/ City[] cityArray=new City[100]; int numCities; public CityGroup() { /** this sets cities to 0; @return numCities **/ numCities=0; } public void addCity(City newCity) { /** this returns the value for ‘cityarray’ after its added @return cityArray[] **/ cityArray[numCities]=newCity; numCities++; }
  • 9. City findNorthMost() { City noa =cityArray[0]; for(int counter=0;counter { if(cityArray[counter].compareTo(noa)==1) noa=cityArray[counter]; } return noa; } } public class City { /** this is main city class @return City **/ int zipcode; String cityName; String state; double latitude; double longitude; int timezone; boolean yesDaylight; public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight) { /** this is constructor for the Class City @return City() **/ zipcode = zip; cityName = cName; state = st; latitude = lat; longitude = lon; timezone = zone; yesDaylight = daylight;
  • 10. } public String toString() { /** this is the toString class @return cityName + "," state; **/ return cityName + ", " + state; } public int compareTo (City otherCity) { /** this is compareTo class to compare @return compareTo; **/ if (otherCity.latitude == latitude) return 0; else if (latitude > otherCity.latitude) return 1; else return -1; } } GUI that i have already: import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(new Font("Serif", Font.PLAIN, 48));
  • 11. paintHorizontallyCenteredText(g2, "City information", 200, 75); } protected void paintHorizontallyCenteredText(Graphics2D g2, String s, float centerX, float baselineY) { FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D bounds = g2.getFont().getStringBounds(s, frc); float width = (float) bounds.getWidth(); g2.drawString(s, centerX - width / 2, baselineY); } **/ main function initializing ‘Frame’ **/ public static void main(String[] args) { JFrame f = new JFrame(); f.getContentPane().add(new Main()); f.setSize(450, 350); f.setVisible(true); } }