105 lines
2.6 KiB
Java
105 lines
2.6 KiB
Java
import java.awt.Point;
|
|
import java.util.ArrayList;
|
|
import java.sql.Connection;
|
|
import java.sql.DriverManager;
|
|
import java.sql.ResultSet;
|
|
import java.sql.SQLException;
|
|
import java.sql.Statement;
|
|
|
|
public class Model {
|
|
private ArrayList<Point> points;
|
|
private ArrayList<ModelListener> listeners;
|
|
|
|
public Model() {
|
|
points = new ArrayList<Point>();
|
|
listeners = new ArrayList<ModelListener>();
|
|
// msw-sh wg. DB-Verbindung
|
|
try (Connection conn = DriverManager.getConnection("jdbc:mysql://msw-sh.local:3306/java", "hmsy",
|
|
"woshimima");
|
|
Statement stmt = conn.createStatement();) {
|
|
ResultSet rs = stmt.executeQuery("SELECT * FROM points");
|
|
while (rs.next()) {
|
|
points.add(new Point(rs.getInt("x"), rs.getInt("y")));
|
|
}
|
|
} catch (SQLException 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();
|
|
}
|
|
|
|
// save to DB
|
|
public void saveData() {
|
|
try (Connection conn = DriverManager.getConnection("jdbc:mysql://msw-sh.local:3306/java", "hmsy",
|
|
"woshimima");
|
|
Statement stmt = conn.createStatement();) {
|
|
// delete all points
|
|
stmt.executeUpdate("DELETE FROM points");
|
|
for (Point p : points) {
|
|
stmt.executeUpdate("INSERT INTO points (x, y) VALUES (" + p.x + ", " + p.y + ")");
|
|
}
|
|
} catch (SQLException e) {
|
|
System.err.println(e.getMessage());
|
|
System.exit(2);
|
|
}
|
|
}
|
|
|
|
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); // Listener called.
|
|
m.addPoint(p2); // Listener called.
|
|
System.out.println(m.numberOfPoints() == 2);
|
|
System.out.println(m.points.get(0) == p1);
|
|
System.out.println(m.points.get(1) == p2);
|
|
m.deleteLastPoint(); // Listener called.
|
|
System.out.println(m.numberOfPoints() == 1);
|
|
System.out.println(m.points.get(0) == p1);
|
|
m.clearAllPoints(); // Listener called.
|
|
System.out.println(m.numberOfPoints() == 0);
|
|
m.notifyListeners(); // Listener called.
|
|
}
|
|
}
|