110 lines
2.4 KiB
Java
110 lines
2.4 KiB
Java
import java.awt.Point;
|
|
import java.util.ArrayList;
|
|
import java.io.FileInputStream;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.ObjectInputStream;
|
|
import java.io.ObjectOutputStream;
|
|
|
|
public class Model {
|
|
private ArrayList<Point> points;
|
|
private ArrayList<ModelListener> listeners;
|
|
|
|
/**
|
|
* Constructor
|
|
*/
|
|
public Model() {
|
|
points = new ArrayList<Point>();
|
|
listeners = new ArrayList<ModelListener>();
|
|
if (new java.io.File("points.bin").exists()) {
|
|
// load points from file
|
|
try {
|
|
FileInputStream fi = new FileInputStream("points.bin");
|
|
ObjectInputStream in = new ObjectInputStream(fi);
|
|
points = (ArrayList<Point>) in.readObject();
|
|
in.close();
|
|
fi.close();
|
|
} catch (IOException e) {
|
|
System.err.println(e.getMessage());
|
|
System.exit(1);
|
|
} catch (ClassNotFoundException e) {
|
|
System.err.println(e.getMessage());
|
|
System.exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void addListener(ModelListener l) {
|
|
listeners.add(l);
|
|
}
|
|
|
|
public ArrayList<Point> getPoints() {
|
|
return points;
|
|
}
|
|
|
|
public void addPoint(Point p) {
|
|
points.add(p);
|
|
notifyListeners();
|
|
}
|
|
|
|
public void clearAllPoints() {
|
|
points.clear();
|
|
notifyListeners();
|
|
}
|
|
|
|
public void deleteLastPoint() {
|
|
if (points.size() > 0) {
|
|
points.remove(points.size() - 1);
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
private void notifyListeners() {
|
|
for (ModelListener l : listeners) {
|
|
l.update();
|
|
}
|
|
}
|
|
|
|
public int numberOfPoints() {
|
|
return points.size();
|
|
}
|
|
|
|
public void saveData() {
|
|
try {
|
|
// save points to file
|
|
FileOutputStream fo = new FileOutputStream("points.bin");
|
|
ObjectOutputStream out = new ObjectOutputStream(fo);
|
|
out.writeObject(points);
|
|
out.close();
|
|
fo.close();
|
|
} catch (IOException e) {
|
|
System.err.println(e.getMessage());
|
|
System.exit(1);
|
|
}
|
|
}
|
|
|
|
public static void testModel() {
|
|
Model m = new Model();
|
|
m.addListener(new ModelListener() {
|
|
@Override
|
|
public void update() {
|
|
System.out.println(true + " (listener)");
|
|
}
|
|
});
|
|
System.out.println(m.getPoints() == m.points);
|
|
Point p1 = new Point(1, 2);
|
|
Point p2 = new Point(3, 4);
|
|
m.addPoint(p1);
|
|
m.addPoint(p2);
|
|
System.out.println(m.numberOfPoints() == 2);
|
|
System.out.println(m.points.get(0) == p1);
|
|
System.out.println(m.points.get(1) == p2);
|
|
m.deleteLastPoint();
|
|
System.out.println(m.numberOfPoints() == 1);
|
|
System.out.println(m.points.get(0) == p1);
|
|
m.clearAllPoints();
|
|
System.out.println(m.numberOfPoints() == 0);
|
|
m.notifyListeners();
|
|
}
|
|
}
|