Problem: On 10/19/2015, we discussed and demonstrated the Facebook example. More
ID: 3762274 • Letter: P
Question
Problem:
On 10/19/2015, we discussed and demonstrated the Facebook example. More details about this example can be found from the PPT slides available at: http://grid.cs.gsu.edu/sims/CSC2310/Content/facebookExample.pdf
Source code of the discussed Facebook example is available at: http://grid.cs.gsu.edu/sims/CSC2310/Content/Facebook.rar (note: use a file compression software such as winzip or winrar to open the rar file). You can run the testFacebook class to see how the program works.
In that example, the testFacebook class uses an array to store the FacebookPersons. The number of FacebookPersons that can be created is limited by the size of the array. Your HW7 is to write another test class named testFacebook_ArrayList that uses ArrayList instead of array to store FacebookPersons. With this new test class, now you can create any number of FacebookPersons.
When your program runs, you will be asked to enter the name for a person to be created. Once you enter a name, a FacebookPerson is created and a window is shown (just like in the Facebook example). If you enter a name that already exists, your program should print a “Name already exist. Try again!” message and asks the user enter another name. After all the persons have been created, you enter #### to end the creation of FacebookPersons. Then the program will ask you to select a person and type the mood. Just like in the Facebook example, when the selected person does not exist, the program prints an “unrecognized name” message; when the mood changes to happy, the corresponding window is displayed with a red background; when you enter ####, the program is terminated.
Create a person with name (enter #### to end the creation of FacebookPersons):
John
FacebookPerson John is created!
Create a person with name (enter #### to end the creation of FacebookPersons):
John
Name already exist. Try again!
Create a person with name (enter #### to end the creation of FacebookPersons):
Alex
FacebookPerson Alex is created!
Create a person with name (enter #### to end the creation of FacebookPersons):
####
-------select a person and type the mood below--------
Enter the name for a person (enter #### to exit):
Alex
Enter the mood for the person:
happy
Enter the name for a person (enter #### to exit):
Mike
unrecognized name!
Enter the name for a person (enter #### to exit):
####
Write the testFacebook_ArrayList class. Do not change the other files. Turn in only the testFacebook_ArrayList.java file. Below is an illustration of how the program runs. Your code must produce the output below AND use an ArrayList instead of an array to store FacebookPersons.
Homework Rubric
0 point
The java code is unrelated
0 point
Cannot compile the java file (due to reasons such
as incorrect java code, incorrect file name, adding
unnecessary package and/or folder structures…)
1 point
Can compile, cannot execute (e.g., exceptions) or
the result is totally wrong
2 points
Can compile, can execute, result is incorrect but
meaningful
3 points
Can compile, can execute, correct result
0 points if an array is used instead of an ArrayList to store FacebookPersons.
Facebook class(main project)
import java.awt.*;
import javax.swing.*;
public class Facebook{
private String name;
private String content;
static DrawingPanel panel = new DrawingPanel(700, 550);
private Graphics g;
public Facebook(String nm){
content = "undefined";
name = nm;
//panel = new DrawingPanel(700, 550);
g = panel.getGraphics();}
// display name
public void setContent(String newContent){
content = newContent;
if(content.equals("happy")){
g.setColor(Color.red);
g.fillRect(489, 30, 200, 150);
g.setColor(Color.black);
g.drawRect(489,30,200,150);
// display mood
g.drawString(name+"'s mood is:"+ "happy", 539, 106);
}
else if(content.equals("sad")){
g.setColor(Color.green);
g.fillRect(10, 370, 200, 150);
g.setColor(Color.black);
g.drawRect(10, 370, 200,150 );
// display mood
g.drawString(name+"'s mood is:"+ "sad", 51, 440);
}
else{
g.setColor(Color.white);
g.fillRect(10, 30, 200, 150);
g.setColor(Color.black);
g.drawRect(10, 30, 200, 150);
g.drawString(name+"'s mood is undefined.", 43, 100); }
}
public String getContent(){
return content;
}
}
FacebookPerson class
public class FacebookPerson{
private String myName;
protected String myMood;
protected Facebook myfacebook;
public FacebookPerson(String name){
myName = name;
myfacebook = new Facebook(myName);
//System.out.println("FacebookPerson's constructor");
}
public FacebookPerson(){
}
public String getName(){
return myName;
}
public void setMood(String newMood){
myMood = newMood;
myfacebook.setContent(myMood);
}
public String getMood(){
return myMood;
}
}
testFacebook class
import java.util.*;
public class testFacebook{
public static void main (String[] args){
// Prompt user to enter the number of facebookpresons
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the number of facebookpresons to be created: ");
int numP = userInput.nextInt();
FacebookPerson[] fbp = new FacebookPerson[numP];
//Ask the user to enter the name for each person, and create the persons
for(int i=0; i< numP; i++){
System.out.println("Enter the name for person "+ (i+1)+ ":");
String name = userInput.next();
fbp[i] = new FacebookPerson(name);
}
System.out.println("-------select a person and type the mood below--------");
//Ask the user to set the mood for a person, and update the mood, enter "####" to exit
while(true){
System.out.println("Enter the name for a person (enter #### to exit):");
String name = userInput.next();
if(name.equals("####"))
System.exit(0);
int personID = -1;
for(int i=0; i< numP; i++){
if(fbp[i].getName().equals(name)){
personID = i;
break;
}
}
if(personID!=-1){ // found the person
System.out.println("Enter the mood for the person:");
String mood = userInput.next();
fbp[personID].setMood(mood);
}
else
System.out.println("unrecognized name!");
} // end while
} // end main
}
DrawingPanel class
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingPanel implements ActionListener {
public static final int DELAY = 50; // delay between repaints in millis
private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save";
private static String TARGET_IMAGE_FILE_NAME = null;
private static final boolean PRETTY = true; // true to anti-alias
private static boolean DUMP_IMAGE = true; // true to write DrawingPanel to file
private int width, height; // dimensions of window frame
private JFrame frame; // overall window frame
private JPanel panel; // overall drawing surface
private BufferedImage image; // remembers drawing commands
private Graphics2D g2; // graphics context for painting
private JLabel statusBar; // status bar showing mouse position
private long createTime;
static {
TARGET_IMAGE_FILE_NAME = System.getProperty(DUMP_IMAGE_PROPERTY_NAME);
DUMP_IMAGE = (TARGET_IMAGE_FILE_NAME != null);
}
// construct a drawing panel of given width and height enclosed in a window
public DrawingPanel(int width, int height) {
this.width = width;
this.height = height;
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.statusBar = new JLabel(" ");
this.statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.panel.setBackground(Color.WHITE);
this.panel.setPreferredSize(new Dimension(width, height));
this.panel.add(new JLabel(new ImageIcon(image)));
// listen to mouse movement
MouseInputAdapter listener = new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
DrawingPanel.this.statusBar.setText("(" + e.getX() + ", " + e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
DrawingPanel.this.statusBar.setText(" ");
}
};
this.panel.addMouseListener(listener);
this.panel.addMouseMotionListener(listener);
this.g2 = (Graphics2D)image.getGraphics();
this.g2.setColor(Color.BLACK);
if (PRETTY) {
this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.g2.setStroke(new BasicStroke(1.1f));
}
this.frame = new JFrame("Building Java Programs - Drawing Panel");
this.frame.setResizable(false);
this.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (DUMP_IMAGE) {
DrawingPanel.this.save(TARGET_IMAGE_FILE_NAME);
}
System.exit(0);
}
});
this.frame.getContentPane().add(panel);
this.frame.getContentPane().add(statusBar, "South");
this.frame.pack();
this.frame.setVisible(true);
if (DUMP_IMAGE) {
createTime = System.currentTimeMillis();
this.frame.toBack();
} else {
this.toFront();
}
// repaint timer so that the screen will update
new Timer(DELAY, this).start();
}
// used for an internal timer that keeps repainting
public void actionPerformed(ActionEvent e) {
this.panel.repaint();
if (DUMP_IMAGE && System.currentTimeMillis() > createTime + 4 * DELAY) {
this.frame.setVisible(false);
this.frame.dispose();
this.save(TARGET_IMAGE_FILE_NAME);
System.exit(0);
}
}
// obtain the Graphics object to draw on the panel
public Graphics2D getGraphics() {
return this.g2;
}
// set the background color of the drawing panel
public void setBackground(Color c) {
this.panel.setBackground(c);
}
// show or hide the drawing panel on the screen
public void setVisible(boolean visible) {
this.frame.setVisible(visible);
}
// makes the program pause for the given amount of time,
// allowing for animation
public void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
// take the current contents of the panel and write them to a file
public void save(String filename) {
String extension = filename.substring(filename.lastIndexOf(".") + 1);
// create second image so we get the background color
BufferedImage image2 = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
Graphics g = image2.getGraphics();
g.setColor(panel.getBackground());
g.fillRect(0, 0, this.width, this.height);
g.drawImage(this.image, 0, 0, panel);
// write file
try {
ImageIO.write(image2, extension, new java.io.File(filename));
} catch (java.io.IOException e) {
System.err.println("Unable to save image: " + e);
}
}
// makes drawing panel become the frontmost window on the screen
public void toFront() {
this.frame.toFront();
}
}
Create a person with name (enter #### to end the creation of FacebookPersons):
John
FacebookPerson John is created!
Create a person with name (enter #### to end the creation of FacebookPersons):
John
Name already exist. Try again!
Create a person with name (enter #### to end the creation of FacebookPersons):
Alex
FacebookPerson Alex is created!
Create a person with name (enter #### to end the creation of FacebookPersons):
####
-------select a person and type the mood below--------
Enter the name for a person (enter #### to exit):
Alex
Enter the mood for the person:
happy
Enter the name for a person (enter #### to exit):
Mike
unrecognized name!
Enter the name for a person (enter #### to exit):
####
Explanation / Answer
/*As per the Question, Only change to the existing program is testFacebook class
Rewriting testFacebook as testFacebook_ArrayList.
All the other classes remain same as existing classes*/
//testFacebook_ArrayList class
import java.util.*;
public class testFacebook_ArrayList
{
public static void main (String[] args)
{
// Prompt user to enter the number of facebookpresons
Scanner userInput = new Scanner(System.in);
ArrayList<FacebookPerson> fbpl=new ArrayList<FacebookPerson>();
//Ask the user to enter the name until #### is entered by user
while(true)
{
System.out.println("Create a person with name (enter #### to end the creation of FacebookPersons):");
String name = userInput.next();
// if user input is ####, break out of while loop
if(name.equals("####"))
break;
// get the size of ArrayList
int arrayListLength = fbpl.size();
for (int i = 0; i < arrayListLength; i++)
{
// Loop through each person in the fpbl and check if input is already present in ArrayList
if (fbpl.get(i).getName().equals(name))
{
// Alert User and Continue the loop asking for another person name
System.out.println("Name already exist. Try again!");
continue;
}
}
// if name is not #### and is not already present in the ArrayList,
// create a new object of FacebookPerson and add it to ArrayList
FacebookPerson fbp = new FacebookPerson(name);
fbpl.add(fbp);
}
System.out.println("-------select a person and type the mood below--------");
//Ask the user to set the mood for a person, and update the mood, enter "####" to exit
while(true)
{
System.out.println("Enter the name for a person (enter #### to exit):");
String name = userInput.next();
// If the user input is ####, exit the program
if(name.equals("####"))
System.exit(0);
int personID = -1;
// get the size of ArrayList
int arrayListLength = fbpl.size();
// Loop through each person in the fpbl
for (int i = 0; i < arrayListLength; i++)
{
// check if input name matches current FacebokPerson in ArrayList
if (fbpl.get(i).getName().equals(name))
{
// set personID to index of person in ArrayList and break out of loop
personID = i;
break;
}
}
if(personID!=-1)
{ // found the person
System.out.println("Enter the mood for the person:");
String mood = userInput.next();
fbpl.get(personID).setMood(mood);
}
else
{
System.out.println("unrecognized name!");
}
} // end while
} // end main
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.