HW4

HW4 – DateTime Parse

private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

// use comma as separator
String[] items = line.split(delimiter);
Date dateTime = null;
try {
      dateTime = formatter.parse(items[0]);
}
catch (ParseException e) {
      e.printStackTrace();
}

/////////////////////////DateParseTest.java////////////////////////////////////////

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.io.FileNotFoundException;
import java.util.*;

public class DateParseTest {
 private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

 public static void main(String[] args)  {
  String date=”1980-12-29 13:00:06″;

  Date dateTime = null;
  try {
   dateTime = formatter.parse(date);
  }
  catch (ParseException e) {
   e.printStackTrace();
  }
  System.out.println(formatter.format(dateTime));
 }
}

Final Exam

기말고사

일시: 2016년 12월 15일 (목) 1:30-3:30

장소: 2공 205호

범위: 중간고사문제 포함 – 중간고사 이후 배운데까지 (수업블로그와 예제 중심으로)

Point Collections

1. create PointLib package
– Point 클래스를 넣는다.
package PointLib;

import java.util.*;

public class Point implements Comparable<Point> {
protected double x;
protected double y;

public Point()
{
this(0.0, 0.0);
}

public Point(double x, double y)
{
this.x = x;
this.y = y;
}

public double getX()
{
return x;
}

public double getY()
{
return y;
}

public int compareTo(Point other)
{
return Double.compare(this.getX(), other.getX()); //ascending order by X
}

public static Comparator<Point> YComparator = new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
};

@Override
public int hashCode() // hashCode method override
{
return Double.valueOf(this.x).hashCode() * Double.valueOf(this.y).hashCode();
}

@Override
public boolean equals(Object obj) // equals method override
{
if (obj instanceof Point)
return equals((Point)obj);
return false;
}

public boolean equals(Point other) // equals method override
{
if (this.x == other.x && this.y == other.y)
return true;
return false;
}

@Override
public String toString() // toString method override
{
return “(” + this.x + “,” + this.y + “)”;
}

}

 

2. create PointCollectionLab package
– PointTest 클래스를 넣는다.
package PointTestApp;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

import PointLib.Point;

class PointTest  {

public static void main(String[] args) {
new PointTest();
}

public PointTest()
{
Point[] pList = new Point[10];
for (int i=0; i<10; i++) {
pList[i] = new Point(i, i+1);
}
System.out.println(“Point!!!”);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT BY X (DEFAULT)!!!”);
Arrays.sort(pList);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Person SORT by Y!!!”);
Arrays.sort(pList, Point.YComparator);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getX(), p2.getX()); //ascending order by X
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getX(), p2.getX())  );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getY(), p2.getY()) );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
ArrayList pointList = new ArrayList();
for (int i=0; i<10; i++) {
pointList.add(new Point(i*10, i*10+1));
}
pointList.forEach((s) -> System.out.println(s));
/*
System.out.println(“Point SORT BY X (lambda)!!!”);
pointList.sort((Point pp1, Point pp2)
-> Double.compare(pp1.getX(), pp2.getX())
);
pointList.forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
pointList.sort((Point p1, Point p2) ->
Double.compare(p1.getY(), p2.getY())
);
pointList.forEach((s) -> System.out.println(s));
*/
System.out.println(“pointList[2]=” + pointList.get(2));

Iterator it = pointList.iterator(); // Iterator 객체 얻기
while(it.hasNext()) {
Object p = it.next();
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Vector vList= new Vector();
for (int i=0; i<10; i++) {
vList.add(new Point(i*100, i*100+1));
}
vList.forEach((s) -> System.out.println(s));

vList.removeElementAt(vList.size() – 1); // delete the last element in vList
for (int i=0; i<vList.size(); i++) {
Object p = vList.get(i);
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Hashtable<Integer, Point> hList = new Hashtable<Integer, Point>();
for (int i=0; i<10; i++) {
hList.put(i, new Point(i*1000, i*1000+1));
}
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“hList contains point (1000, 1001) is ” + hList.contains(new Point(1000, 1001)));
hList.put(10, new Point(10, 10));
hList.forEach((i, s) -> System.out.println(s));
hList.remove(9); // remove item by key
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“Key,Value print”);
Set keys = hList.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()) {
Integer key = (Integer) itr.next();
Point value = hList.get(key);
System.out.println(“(” + key + “,” + value + “)”);
}

///////////////////////////////////////////////////////////////////////
System.out.println(“/////////////”);
}
}

Person FileIO & JTable

Person ArrayList & FileIO & JTable & CustomDialog & Menu

1. Person 클래스

import java.util.*;

enum Gender
{
FEMALE, MALE
}

public class Person implements Comparable<Person>
{
private String name;
private int age;
private double weight;
private double height;
private Gender gender;

public Person()
{
this(“”, 0, 0.0, 0.0, Gender.FEMALE);
}

public Person(String name, int age, double weight, double height, Gender gender)
{
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
this.gender = gender;
}

public Person(Person other)
{
this(other.name, other.age, other.weight, other.height, other.gender);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public double getWeight()
{
return weight;
}

public void setWeight(double weight)
{
this.weight = weight;
}

public double getHeight()
{
return height;
}

public void setHeight(double height)
{
this.height = height;
}

public Gender getGender()
{
return gender;
}

public void setGender(Gender gender)
{
this.gender = gender;
}

@Override
public String toString() // Object.toString() overriding
{
return String.format(“%s,%d,%.2f,%.2f,%s”, name, age, weight, height, gender.toString());
}

@Override
public boolean equals(Object other) // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this)
&& this.getName().equals(that.getName())
&& this.getAge() == that.getAge()
&& this.getWeight() == that.getWeight()
&& this.getHeight() == that.getHeight()
&& this.getGender() == that.getGender();
}
return false;
}

@Override
public int hashCode()
{
return (41 * getName().hashCode() + getAge() + Double.valueOf(getWeight()).hashCode() + Double.valueOf(getHeight()).hashCode() + (int)(getGender()).hashCode());
}

public boolean canEqual(Object other)
{
return (other instanceof Person);
}

public int compareTo(Person other)
{
return this.getName().compareTo(other.getName()); //ascending order
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge() – p2.getAge(); //ascending order
}
};

public static Comparator<Person> WeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getWeight(), p2.getWeight()); //ascending order
}
};

public static Comparator<Person> HeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getHeight(), p2.getHeight()); //ascending order
}
};

public static Comparator<Person> GenderComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getGender().compareTo(p2.getGender());
}
};

}

2. PersonDialog 클래스

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

//Kyoung Shin Park (2016 Fall)
public class PersonDialog extends JDialog implements ActionListener {

public final static int OK = 1;
public final static int CANCEL = 2;
int returnValue = 0;

JLabel label1 = new JLabel(“이름”); // 레이블 초기화
JLabel label2 = new JLabel(“나이”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게”); // 레이블 초기화
JLabel label4 = new JLabel(“키”); // 레이블 초기화
JLabel label5 = new JLabel(“성별”); // 레이블 초기화

JTextField textfield1 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield2 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield4 = new JTextField(20); // 텍스트필드 초기화

JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
ButtonGroup rgroup = new ButtonGroup();
JPanel panel = new JPanel(); // 패널 초기화

JButton button1 = new JButton(“확인”); // 버튼 초기화

Person person = new Person();

public PersonDialog() {
setTitle(“Person Dialog”);
setLayout(null);

// frame
label1.setBounds(20, 30, 100, 20);
label2.setBounds(20, 60, 100, 20);
label3.setBounds(20, 90, 100, 20);
label4.setBounds(20, 120, 100, 20);
label5.setBounds(20, 150, 100, 20);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);

textfield1.setBounds(120, 30, 150, 20);
textfield2.setBounds(120, 60, 150, 20);
textfield3.setBounds(120, 90, 150, 20);
textfield4.setBounds(120, 120, 150, 20);

add(textfield1);
add(textfield2);
add(textfield3);
add(textfield4);
panel.add(rbutton1);
panel.add(rbutton2);
rgroup.add(rbutton1);
rgroup.add(rbutton2);
panel.setBounds(20, 150, 300, 40);
add(panel);

button1.setBounds(60, 200, 160, 20);
add(button1);

// event
button1.addActionListener(this);

setSize(300, 270); // size the frame
setResizable(false);
setModal(true);
}

private Gender selectGender()
{
if (rbutton2.isSelected()) {
return Gender.MALE;
}
return Gender.FEMALE;
}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
person.setName(textfield1.getText());
person.setAge(Integer.parseInt(textfield2.getText()));
person.setWeight(Double.parseDouble(textfield3.getText()));
person.setHeight(Double.parseDouble(textfield4.getText()));
person.setGender(selectGender());
returnValue = OK;
dispose();
}
}

public int getReturnValue()
{
return returnValue;
}

public Person getPerson()
{
return person;
}

/*public static void main(String[] args) {
new PersonDialog();
}*/
}

3. PersonTableModel 클래스

import java.util.*;
import javax.swing.table.*;

public class PersonTableModel extends AbstractTableModel {

private ArrayList<Person> personList;

public PersonTableModel(ArrayList<Person> pList) {
this.personList = new ArrayList<Person>(pList);
}

@Override
public int getRowCount() {
return this.personList.size();
}

@Override
public int getColumnCount() {
return 5;
}

@Override
public String getColumnName(int column) {
String name = “??”;
switch (column) {
case 0:
name = “Name”;
break;
case 1:
name = “Age”;
break;
case 2:
name = “Weight”;
break;
case 3:
name = “Height”;
break;
case 4:
name = “Gender”;
break;
}
return name;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
Class<?> type = String.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
case 2:
case 3:
type = Double.class;
break;
case 4:
type = Gender.class;
break;
}
return type;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = this.personList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = p.getName();
break;
case 1:
value = p.getAge();
break;
case 2:
value = p.getWeight();
break;
case 3:
value = p.getHeight();
break;
case 4:
value = p.getGender();
break;
}
return value;
}

public void setValueAt(Person value, int rowIndex) {
this.personList.set(rowIndex, value);
fireTableDataChanged();
}

public void addRow(Person p) {
this.personList.add(p);
fireTableRowsInserted(this.personList.size() – 1, this.personList.size() – 1);
}

public void removeRow(int rowIndex) {
if (rowIndex >=0 && rowIndex < getRowCount()) {
this.personList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
}

4. PersonTableFrame 클래스

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.io.*;

//Kyoung Shin Park (2016 Fall)
public class PersonTableFrame extends JFrame {

ArrayList<Person> personList = new ArrayList<Person>();
PersonTableModel model;

public PersonTableFrame()
{
super(“PersonTableFrame”);

model = new PersonTableModel(personList);
JTable table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setIntercellSpacing(new Dimension(10, 5));
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
int index = table.getSelectedRow();
if (index >= 0 && index < personList.size()) {
personList.remove(index);
model.removeRow(index);
//personList.forEach((s) -> System.out.println(s));
}
}
});
/*.add(new Person(“Dooly”, 1000, 40, 126.4, Gender.MALE));
personList.add(new Person(“Douner”, 1986, 30, 110, Gender.MALE));
personList.add(new Person(“Ddochi”, 30, 50, 150.5, Gender.MALE));
personList.add(new Person(“Heedong”, 3, 36, 100.6, Gender.MALE));
personList.add(new Person(“Michol”, 25, 39.8, 126.4, Gender.MALE));
personList.add(new Person(“Gildong”, 40, 38.2, 129.4, Gender.MALE));
personList.add(new Person(“Younghi”, 10, 47.2, 152.4, Gender.FEMALE));
personList.add(new Person(“Cheolsoo”, 10, 48.2, 155.4, Gender.MALE));
personList.forEach((s) -> System.out.println(s));
personList.forEach((s) -> model.addRow(s));*/

personList = loadCSV(“data/PersonList.csv”);
personList.forEach((s) -> model.addRow(s));
//personList.forEach((s) -> System.out.println(s));
//saveCSV(“TestList.csv”, personList);

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane, BorderLayout.CENTER);

// menu
JMenuBar menuBar = new JMenuBar();

// File Menu, F – Mnemonic
JMenu fileMenu = new JMenu(“File”);
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);

// File->Open, O – Mnemonic
JMenuItem openMenuItem = new JMenuItem(“Open”, KeyEvent.VK_O);
fileMenu.add(openMenuItem);
this.setJMenuBar(menuBar);
openMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“OPEN”);
String selectedFilename = openFileDialog();
if (selectedFilename != null) {
personList = loadCSV(selectedFilename);
personList.forEach((q) -> model.addRow(q));
}
}
});

// File->Save, O – Mnemonic
JMenuItem saveMenuItem = new JMenuItem(“Save”, KeyEvent.VK_S);
fileMenu.add(saveMenuItem);
this.setJMenuBar(menuBar);
saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“SAVE”);
String selectedFilename = saveFileDialog();
if (selectedFilename != null) {
saveCSV(selectedFilename, personList);
}
}
});

// File->Exit, E – Mnemonic
JMenuItem exitMenuItem = new JMenuItem(“Exit”, KeyEvent.VK_E);
fileMenu.add(exitMenuItem);
this.setJMenuBar(menuBar);
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.exit(0);
}
});

// Person Menu, P – Mnemonic
JMenu personMenu = new JMenu(“Person”);
personMenu.setMnemonic(KeyEvent.VK_P);
menuBar.add(personMenu);

// Person->Add, A – Mnemonic
JMenuItem addMenuItem = new JMenuItem(“Add”, KeyEvent.VK_A);
personMenu.add(addMenuItem);
this.setJMenuBar(menuBar);
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
PersonDialog personDialog = new PersonDialog();
personDialog.setVisible(true);
if (personDialog.getReturnValue() == PersonDialog.OK) {
Person p = personDialog.getPerson();
//System.out.println(p);
model.addRow(p);
personList.add(p);
System.out.println(“After add:”);
personList.forEach((s) -> System.out.println(s));
System.out.println(“———————added”);
}
}
});

this.setSize(600, 450);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public String openFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“openFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not opened”);
return null;
}
}

public String saveFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“saveFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not selected”);
return null;
}
}

// load CSV
public ArrayList<Person> loadCSV(String filename)
{
ArrayList<Person> pList = new ArrayList<Person>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
System.out.println(“file import: ” + filename);

String line = “”;
String delimiter = “,”;

while ((line = br.readLine()) != null) {
// use comma as separator
String[] items = line.split(delimiter);
String name = items[0];
int age = Integer.parseInt(items[1]);
double weight = Double.parseDouble(items[2]);
double height = Double.parseDouble(items[3]);
Gender gender = items[4].equals(“FEMALE”) ? Gender.FEMALE : Gender.MALE;

// add Person into List
Person p = new Person(name, age, weight, height, gender);
//System.out.println(p);
pList.add(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“load successfully”);
return pList;
}

// save CSV
public void saveCSV(String path, ArrayList<Person> pList)
{
FileWriter fw;
try {
System.out.println(“file save: ” + path);

fw = new FileWriter(path);
for (Person p : pList) {
System.out.println(p);
fw.append(p.toString() + “\n”);
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String args[])
{
new PersonTableFrame(); // data table
}

}

PointLib & ShapeDrawing

1. create a package (PointLib)

1.1 Point 클래스를 추가한다.
PointLib

 

2. create a package (ShapeApp)

ShapeApp

2.1. RandomShape 클래스를 추가한다.

 

package ShapeApp;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

public class RandomShape {
Shape shape;
Color color;

RandomShape(Shape s, Color c) {
shape = s;
color = c;
}

public Shape getShape() {
return shape;
}

public void draw(Graphics2D g) {
g.setColor(color);
g.fill(shape);
}

boolean contains(int x, int y) {
return shape.contains((double) x, (double) y);
}

void translate(int x, int y) {
if (shape instanceof Polygon) {
Polygon p = (Polygon) shape;
p.translate(x, y);
}
else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle) shape;
r.translate(x, y);
}
else if (shape instanceof Ellipse2D) {
Ellipse2D e = (Ellipse2D) shape;
e.setFrame((double) x, (double) y, e.getWidth(), e.getHeight());
}
}
}

2.2. RandomShapeFactory 클래스를 추가한다.

package ShapeApp;

import java.awt.Color;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.util.Random;

import PointLib.Point;

public class RandomShapeFactory {

private static Random rand = new Random();

public static Color randomColor() {
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
return new Color(r, g, b);
}

public static int randomInt(int min, int max) {
return rand.nextInt(max-min) + min;
}

public static RandomShape getInstance(Point center) {
int shapeType = rand.nextInt() % 3;
System.out.println(“ShapeType=” + shapeType);
switch (shapeType) {
case 1:
{
System.out.println(“Triangle”);
int size = randomInt(20, 30);
Polygon triangle = new Polygon();
triangle.addPoint((int) center.getX(), (int) center.getY());
triangle.addPoint((int) (center.getX()-size), (int) (center.getY()+size));
triangle.addPoint((int) (center.getX()+size), (int) (center.getY()+size));
RandomShape s = new RandomShape(triangle, randomColor());
return s;
}

case 2:
{
System.out.println(“Rectangle”);
Shape rectangle = new Rectangle((int) center.getX(), (int) center.getY(), randomInt(50, 60), randomInt(50, 60));
RandomShape s= new RandomShape(rectangle, randomColor());
return s;
}

default:
{
System.out.println(“Oval”);
Shape oval = new Ellipse2D.Double(center.getX(), center.getY(), randomInt(40, 50), randomInt(30, 40));
RandomShape s= new RandomShape(oval, randomColor());
return s;
}
}
}
}

2.3. ShapeDrawing 클래스를 추가한다.

package ShapeApp;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;

import PointLib.Point;

// ShapeDrawing
public class ShapeDrawing extends JFrame {
ShapeDrawingPanel polyCanvas = new ShapeDrawingPanel();

public static void main(String[] args) {
    new ShapeDrawing();
}

public ShapeDrawing() {
super(“Shape Drawing Frame”);

setBounds(10, 10, 350, 350);
setResizable(false);
setVisible(true);

polyCanvas.setPreferredSize(new Dimension(300, 300));
this.add(polyCanvas);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private class ShapeDrawingPanel extends JPanel implements MouseListener, MouseMotionListener
{
int lastX, lastY;
boolean dragging = false;

ArrayList<RandomShape> shapes = new ArrayList<RandomShape>();
RandomShape selectedShape = null;

public ShapeDrawingPanel()
{
System.out.println(“ShapeDrawingPanel”);
addMouseListener(this);
addMouseMotionListener(this);
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

for (RandomShape s : shapes)
s.draw(g2);
}

RandomShape findShape(int x, int y)
{
RandomShape s = null;
for (int i = shapes.size() – 1; i >= 0; i–) {
s = (RandomShape) shapes.get(i);
if (s.contains(x, y)) {
System.out.println(“Selected”);
return s;
}
}
return null;
}

public void mouseDragged(MouseEvent e) {
if (dragging == true) {
if (selectedShape.getShape() instanceof Ellipse2D)
selectedShape.translate(e.getX(), e.getY());
else {
int deltaX = e.getX() – lastX;
int deltaY = e.getY() – lastY;
System.out.println(“x = ” + deltaX + ” y = ” + deltaY);
selectedShape.translate(deltaX, deltaY);
lastX = e.getX();
lastY = e.getY();
}
repaint();
}
}

public void mouseMoved(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
selectedShape = findShape(e.getX(), e.getY());
if (selectedShape != null) {
dragging = true;
lastX = e.getX();
lastY = e.getY();
}
else {
System.out.println(“Pressed”);
RandomShape s = RandomShapeFactory.getInstance(new Point((double) e.getX(), (double) e.getY()));
shapes.add(s);
repaint(); // calls paintComponent()
}
}

public void mouseReleased(MouseEvent e) {
if (dragging == true) {
dragging = false;
selectedShape = null;
}
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}
}
}