Refactoring

* package refactoring
* new matrix implementation (todo)
* new adj list implemetation (todo)
* fixed tests
This commit is contained in:
2019-06-15 15:15:13 +02:00
parent a8596331e7
commit 0de35fd4a1
35 changed files with 772 additions and 118 deletions

View File

@@ -0,0 +1,214 @@
package berack96.lib.graph.view;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import berack96.lib.graph.Graph;
import berack96.lib.graph.view.edge.EdgeListener;
import berack96.lib.graph.view.vertex.VertexListener;
import berack96.lib.graph.visit.VisitStrategy;
public class GraphInfo<V, W extends Number> extends JPanel {
private static final long serialVersionUID = 1L;
private final Map<String, VisitListener<V>> visits;
public GraphInfo(GraphPanel<V, W> graphPanel, VertexListener<V> vListener, EdgeListener<V, W> eListener, Set<VisitStrategy<V, W>> visits) {
this.visits = new HashMap<>();
/* ZERO (DESCRIPTION) */
JLabel listenerDescription = new JLabel();
JPanel panelDescription = new JPanel();
panelDescription.setOpaque(false);
panelDescription.add(listenerDescription);
/* FIRST (GRAPH INFO) */
JLabel vNumber = new JLabel(String.valueOf(graphPanel.getGraph().numberOfVertices()));
JLabel eNumber = new JLabel(String.valueOf(graphPanel.getGraph().numberOfEdges()));
JLabel gCyclic = new JLabel(String.valueOf(graphPanel.getGraph().isCyclic()));
List<Component> components = new LinkedList<>();
JLabel selected = new JLabel();
JComboBox<String> comboBox = new JComboBox<>();
comboBox.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
String clazz = (String) e.getItem();
VisitListener<V> listener = this.visits.get(clazz);
selected.setText(listener != null? "visit":"nothing");
listenerDescription.setText(listener != null? listener.getDescription():"");
graphPanel.getGraph().unMarkAll();
graphPanel.repaint();
graphPanel.setGraphListener(listener);
} catch (Exception ignore) {}
}
});
comboBox.addItem("None");
for(VisitStrategy<V, W> strategy: visits) {
String clazz = strategy.getClass().getSimpleName();
VisitListener<V> visit = new VisitListener<>(graphPanel, strategy);
comboBox.addItem(clazz);
this.visits.put(clazz, visit);
}
components.add(new JLabel("Visit Strategy: "));
components.add(comboBox);
components.add(new JLabel("Selected modality: "));
components.add(selected);
components.add(new JLabel("Vertex Number: "));
components.add(vNumber);
components.add(new JLabel("Edge Number: "));
components.add(eNumber);
components.add(new JLabel("Is Cyclic: "));
components.add(gCyclic);
JPanel panelInfo = new JPanel();
panelInfo.setOpaque(false);
panelInfo.setBorder(BorderFactory.createLineBorder(Color.RED));
panelInfo.setLayout(new GridLayout(components.size()/2, 2, 2*2, 2*2));
components.forEach(panelInfo::add);
components.clear();
/* SECOND (VERTEX) */
JLabel vVertex = new JLabel();
JLabel vEdgesNumber = new JLabel();
JLabel vEdgesInNumber = new JLabel();
JLabel vEdgesOutNumber = new JLabel();
JButton modVertex = new JButton("Modify Vertices");
modVertex.addActionListener(a -> {
comboBox.setSelectedIndex(0);
listenerDescription.setText(vListener.getDescription());
graphPanel.setGraphListener(vListener);
graphPanel.getGraph().unMarkAll();
graphPanel.repaint();
selected.setText("vertices");
});
JButton modEdge = new JButton("Modify Edges");
modEdge.addActionListener(a -> {
comboBox.setSelectedIndex(0);
listenerDescription.setText(eListener.getDescription());
graphPanel.setGraphListener(eListener);
graphPanel.getGraph().unMarkAll();
graphPanel.repaint();
selected.setText("edges");
});
components.add(modVertex);
components.add(modEdge);
components.add(new JLabel("Vertex name: "));
components.add(vVertex);
components.add(new JLabel("Edges: "));
components.add(vEdgesNumber);
components.add(new JLabel("Edges IN: "));
components.add(vEdgesInNumber);
components.add(new JLabel("Edges OUT: "));
components.add(vEdgesOutNumber);
JPanel panelVertex = new JPanel();
panelVertex.setOpaque(false);
panelVertex.setLayout(new GridLayout(components.size()/2, 2, 2*2, 2*2));
components.forEach(panelVertex::add);
components.clear();
/* SAVE/LOAD errors */
JLabel textResult = new JLabel();
textResult.setForeground(Color.RED);
JPanel panelErrors = new JPanel();
panelErrors.setOpaque(false);
panelErrors.add(textResult);
/* SAVE/LOAD */
JTextField fileText = new JTextField();
JButton saveB = new JButton("Save");
saveB.addActionListener(a -> {
try {
graphPanel.save(fileText.getText());
textResult.setText("");
} catch (IOException e1) {
textResult.setText(e1.getMessage());
}
});
JButton loadB = new JButton("Load");
loadB.addActionListener(a -> {
try {
graphPanel.load(fileText.getText());
textResult.setText("");
} catch (IOException e1) {
textResult.setText(e1.getMessage());
}
});
components.add(new JLabel("File to save/load: "));
components.add(fileText);
components.add(saveB);
components.add(loadB);
JPanel panelSave = new JPanel();
panelSave.setOpaque(false);
panelSave.setBorder(BorderFactory.createLineBorder(Color.RED));
panelSave.setLayout(new GridLayout(components.size()/2, 2, 2*2, 2*2));
components.forEach(panelSave::add);
components.clear();
/* ADDING COMPONENTS */
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setOpaque(true);
this.setBorder(BorderFactory.createSoftBevelBorder(BevelBorder.RAISED, Color.GRAY, Color.DARK_GRAY));
this.add(panelDescription);
this.add(panelInfo);
this.add(panelVertex);
this.add(panelErrors);
this.add(panelSave);
/*this.add(panelSave);*/
modVertex.doClick();
graphPanel.addObserver((o, arg) -> {
Graph<V, W> graph = graphPanel.getGraph();
if(arg.equals(graph)) {
vNumber.setText(String.valueOf(graph.numberOfVertices()));
eNumber.setText(String.valueOf(graph.numberOfEdges()));
gCyclic.setText(String.valueOf(graph.isCyclic()));
/* There should be only one */
for(V v : graph.getMarkedWith("selected")) {
int inE = graph.getEdgesIn(v).size();
int outE = graph.getEdgesOut(v).size();
vEdgesInNumber.setText(String.valueOf(inE));
vEdgesOutNumber.setText(String.valueOf(outE));
vEdgesNumber.setText(String.valueOf(inE + outE));
vVertex.setText(v.toString());
}
}
});
}
}

View File

@@ -0,0 +1,27 @@
package berack96.lib.graph.view;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
* An interface for creating a listener of the Graph.
*
* @author Berack96
*/
public interface GraphListener extends MouseListener, MouseMotionListener, KeyListener {
/**
* Remove the listener to the graph.
* This function is called when the listener is removed to the graph.
* Here you could remove any other thing that you have done.
*/
public void remove();
/**
* Get the description of this listener, in a way to interact with the user.
*
* @return a string describing the functionalities of this listener
*/
public String getDescription();
}

View File

@@ -0,0 +1,265 @@
package berack96.lib.graph.view;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Observer;
import java.util.Set;
import berack96.lib.graph.Edge;
import berack96.lib.graph.Graph;
import berack96.lib.graph.Vertex;
import berack96.lib.graph.impl.MapGraph;
import berack96.lib.graph.view.edge.EdgeComponent;
import berack96.lib.graph.view.vertex.VertexComponent;
@SuppressWarnings({"unchecked", "deprecation"})
public class GraphPanel<V, W extends Number> extends Component {
private static final long serialVersionUID = 1L;
private final GraphicalView<VertexComponent<V>> vertexRender;
private final GraphicalView<EdgeComponent<V, W>> edgeRender;
private final Class<V> classV;
private final Class<W> classW;
private final Container vertices = new Container();
private final Container edges = new Container();
private final Graph<V, W> graph = new MapGraph<>();
private final Set<Observer> observers = new HashSet<>();
private GraphListener old = null;
public GraphPanel(GraphicalView<VertexComponent<V>> vertexRender, GraphicalView<EdgeComponent<V, W>> edgeRender, Class<V> classV, Class<W> classW) {
this.vertexRender = vertexRender;
this.edgeRender = edgeRender;
this.classV = classV;
this.classW = classW;
}
public Graph<V, W> getGraph() {
return graph;
}
public void setGraphListener(GraphListener listener) {
if(old != null)
old.remove();
for (MouseListener l : getMouseListeners())
removeMouseListener(l);
for (MouseMotionListener l : getMouseMotionListeners())
removeMouseMotionListener(l);
for (KeyListener l : getKeyListeners())
removeKeyListener(l);
old = listener;
addMouseListener(listener);
addMouseMotionListener(listener);
addKeyListener(listener);
}
public void addVertex(Point center, V vertex) {
VertexComponent<V> component = getVertexAt(center);
if (component == null) {
VertexComponent<V> v = new VertexComponent<>(new Vertex<>(graph, vertex));
v.vertex.addIfAbsent();
boolean isContained = false;
for(Component comp : vertices.getComponents())
if (comp.equals(v))
isContained = true;
if (!isContained) {
v.setBounds(vertexRender.getBox(v, center));
vertices.add(v);
}
}
}
public void removeVertex(Point center) {
try {
VertexComponent<V> component = getVertexAt(center);
component.vertex.remove();
vertices.remove(component);
} catch (Exception ignore) {}
}
public void moveVertex(VertexComponent<V> vertex, Point destination) {
Rectangle rectangle = vertexRender.getBox(vertex, destination);
vertex.setLocation(rectangle.x, rectangle.y);
}
public void addEdge(Edge<V, W> edge) {
VertexComponent<V> vSource = null;
VertexComponent<V> vDest = null;
for (Component comp : vertices.getComponents()) {
VertexComponent<V> temp = (VertexComponent<V>) comp;
V vTemp = temp.vertex.getValue();
if (vSource == null && vTemp.equals(edge.getSource()))
vSource = temp;
if (vDest == null && vTemp.equals(edge.getDestination()))
vDest = temp;
}
addEdge(vSource, vDest, edge.getWeight());
}
public void addEdge(VertexComponent<V> source, VertexComponent<V> dest, W weight) {
try {
Point center = new Point(Math.abs(source.getX() - dest.getY()), Math.abs(source.getY() - dest.getY()));
EdgeComponent<V, W> edgeComponent = new EdgeComponent<>(source, dest, weight);
edgeComponent.setBounds(edgeRender.getBox(edgeComponent, center));
edges.add(edgeComponent);
graph.addEdge(edgeComponent.edge);
} catch (Exception ignore) {
ignore.printStackTrace();
}
}
public void removeEdge(VertexComponent<V> source, VertexComponent<V> dest) {
try {
graph.removeEdge(source.vertex.getValue(), dest.vertex.getValue());
EdgeComponent<V, W> toRemove = null;
for (Component c : edges.getComponents()) {
EdgeComponent<V, W> edge = (EdgeComponent<V, W>) c;
if (edge.source.equals(source) && edge.destination.equals(dest))
toRemove = edge;
}
edges.remove(toRemove);
} catch (Exception ignore) {}
}
public void modEdge(VertexComponent<V> source, VertexComponent<V> dest, W weight) {
removeEdge(source, dest);
addEdge(source, dest, weight);
}
public VertexComponent<V> getVertexAt(Point point) {
Component component = vertices.getComponentAt(point);
return component instanceof VertexComponent ? (VertexComponent<V>) component : null;
}
public EdgeComponent<V, W> getEdgeAt(Point point) {
Component component = edges.getComponentAt(point);
return component instanceof EdgeComponent ? (EdgeComponent<V, W>) component : null;
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void save(String fileName) throws IOException {
GraphGraphicalSave save = new GraphGraphicalSave(vertices);
Graph.save(graph, Graph.GSON.toJson(save), fileName);
}
public void load(String fileName) throws IOException {
String saveContent = Graph.load(graph, fileName, classV, classW);
GraphGraphicalSave save = Graph.GSON.fromJson(saveContent, GraphGraphicalSave.class);
vertices.removeAll();
edges.removeAll();
for(int i = 0; i<save.vertices.length; i++) {
V v = Graph.GSON.fromJson(save.vertices[i], classV);
Point p = save.points[i];
addVertex(p, v);
}
for(String v : save.vertices)
graph.getEdgesOut(Graph.GSON.fromJson(v, classV)).forEach(e -> addEdge(e));
repaint();
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
vertices.setBounds(x, y, width, height);
edges.setBounds(x, y, width, height);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Collection<EdgeComponent<V, W>> toRemove = new HashSet<>();
for (Component component : edges.getComponents()) {
EdgeComponent<V, W> edge = (EdgeComponent<V, W>) component;
Vertex<V> source = edge.source.vertex;
Vertex<V> dest = edge.destination.vertex;
if (source.isStillContained() && dest.isStillContained() && graph.containsEdge(source.getValue(), dest.getValue())) {
Point center = new Point(edge.getX() + edge.getWidth() / 2, edge.getY() + edge.getHeight() / 2);
edge.setBounds(edgeRender.getBox(edge, center));
edgeRender.paint((Graphics2D) g2.create(), edge, center);
}
else
toRemove.add(edge);
}
toRemove.forEach(edges::remove);
for (Component component : vertices.getComponents()) {
VertexComponent<V> vertex = (VertexComponent<V>) component;
if (graph.contains(vertex.vertex.getValue())) {
Point center = new Point(vertex.getX() + vertex.getWidth() / 2, vertex.getY() + vertex.getHeight() / 2);
vertexRender.paint((Graphics2D) g2.create(), vertex, center);
}
}
updateObservers();
}
private void updateObservers() {
observers.forEach(observer -> observer.update(null, this.graph));
}
class GraphGraphicalSave {
public GraphGraphicalSave() {}
protected GraphGraphicalSave(Container vertices) {
List<String> v = new LinkedList<>();
List<Point> p = new LinkedList<>();
for(Component vertex : vertices.getComponents()) {
Point temp = new Point(vertex.getX(), vertex.getY());
temp.x += vertex.getWidth() / 2;
temp.y += vertex.getHeight() / 2;
p.add(temp);
v.add(Graph.GSON.toJson(((VertexComponent<V>) vertex).vertex.getValue()));
}
int i = 0;
this.vertices = new String[v.size()];
for(String s : v) {
this.vertices[i] = s;
i++;
}
i = 0;
this.points = new Point[p.size()];
for(Point pt : p) {
this.points[i] = pt;
i++;
}
}
public String[] vertices;
public Point[] points;
}
}

View File

@@ -0,0 +1,68 @@
package berack96.lib.graph.view;
import berack96.lib.graph.view.edge.EdgeIntListener;
import berack96.lib.graph.view.edge.EdgeListener;
import berack96.lib.graph.view.edge.EdgeView;
import berack96.lib.graph.view.vertex.VertexIntListener;
import berack96.lib.graph.view.vertex.VertexListener;
import berack96.lib.graph.view.vertex.VertexView;
import berack96.lib.graph.visit.*;
import berack96.lib.graph.visit.impl.BFS;
import berack96.lib.graph.visit.impl.DFS;
import berack96.lib.graph.visit.impl.Dijkstra;
import berack96.lib.graph.visit.impl.Tarjan;
import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class is the Window that appear for building the graph and playing around with it
*
* @author Berack96
*/
public class GraphWindow<V, W extends Number> extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
GraphPanel<Integer, Integer> panel = new GraphPanel<>(new VertexView<>(), new EdgeView<>(), Integer.class, Integer.class);
GraphWindow<Integer, Integer> win = new GraphWindow<>(panel, new VertexIntListener(panel), new EdgeIntListener<>(panel));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // full screen
dim.setSize(dim.width / 2, dim.height / 2);
win.setSize(dim);
win.setLocationRelativeTo(null); //centered
win.visitRefresh(500);
win.setVisible(true);
}
private final GraphPanel<V, W> graphPanel;
private final GraphInfo<V, W> infoPanel;
private GraphWindow(GraphPanel<V, W> graphPanel, VertexListener<V> vListener, EdgeListener<V, W> eListener) {
this.setTitle("Grafo");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
Set<VisitStrategy<V, W>> strats = new LinkedHashSet<>();
strats.add(new DFS<>());
strats.add(new BFS<>());
strats.add(new Dijkstra<>());
strats.add(new Tarjan<>());
this.infoPanel = new GraphInfo<>(graphPanel, vListener, eListener, strats);
this.graphPanel = graphPanel;
this.add(infoPanel, BorderLayout.EAST);
this.add(graphPanel);
}
public void visitRefresh(int millisec) {
VisitListener.changeRefresh(millisec);
}
public GraphPanel<V, W> getGraphPanel() {
return graphPanel;
}
}

View File

@@ -0,0 +1,30 @@
package berack96.lib.graph.view;
import java.awt.*;
/**
* An interface for divide the "hitbox" and the "paint" of the various items
*
* @param <O> the object to paint
* @author Berack96
*/
public interface GraphicalView<O> {
/**
* Box where the object is sensible at listeners (like Hitbox)
*
* @param obj the object to draw
* @param center the center point of the object
* @return a rectangle where the object is sensible to the listeners
*/
Rectangle getBox(O obj, Point center);
/**
* The paint function, aka the part where you can draw things (like Mesh)
*
* @param g2 the graphics object used for painting
* @param obj the object to paint
* @param center the center point of the object
*/
void paint(Graphics2D g2, O obj, Point center);
}

View File

@@ -0,0 +1,112 @@
package berack96.lib.graph.view;
import berack96.lib.graph.Graph;
import berack96.lib.graph.view.vertex.VertexComponent;
import berack96.lib.graph.visit.VisitStrategy;
import berack96.lib.graph.visit.impl.VisitInfo;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class VisitListener<V> implements GraphListener {
private final GraphPanel<V, ?> panel;
private final VisitStrategy<V, ?> strategy;
private final Set<Timer> timers = new HashSet<>();
private static int refreshTime = 1000;
public VisitListener(GraphPanel<V, ?> panel, VisitStrategy<V, ?> strategy) {
this.panel = panel;
this.strategy = strategy;
}
public static void changeRefresh(int millisec) {
refreshTime = millisec;
}
@Override
public void remove() {
timers.forEach(t -> t.stop());
timers.clear();
}
@Override
public String getDescription() {
return "<html>"
+ "Start a visit by pressing<br />"
+ "with the mouse SX on the root vertex<br />"
+ "</html>";
}
@Override
public void mousePressed(MouseEvent e) {
this.remove();
Graph<V, ?> graph = panel.getGraph();
graph.unMarkAll();
panel.repaint();
if (e.getButton() == MouseEvent.BUTTON1)
try {
VertexComponent<V> vertex = panel.getVertexAt(e.getPoint());
AtomicInteger count = new AtomicInteger(0);
VisitInfo<V> info = vertex.vertex.visit(strategy, null);
info.forEach(v -> {
final boolean visited = v.timeVisited == count.get();
Timer timer = new Timer(count.getAndIncrement() * refreshTime, e1 -> {
if (visited && v.parent !=null)
graph.mark(v.vertex, v.parent);
graph.mark(v.vertex, visited ? "visited" : "discovered");
panel.repaint();
});
timers.add(timer);
timer.setRepeats(false);
timer.start();
});
} catch (Exception ignore) {}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}

View File

@@ -0,0 +1,22 @@
package berack96.lib.graph.view.edge;
import berack96.lib.graph.Edge;
import berack96.lib.graph.view.vertex.VertexComponent;
import java.awt.*;
public class EdgeComponent<V, W extends Number> extends Component {
private static final long serialVersionUID = 1L;
public final VertexComponent<V> source;
public final VertexComponent<V> destination;
public final W weight;
public final Edge<V, W> edge;
public EdgeComponent(VertexComponent<V> source, VertexComponent<V> destination, W weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
this.edge = new Edge<>(source.vertex.getValue(), destination.vertex.getValue(), weight);
}
}

View File

@@ -0,0 +1,24 @@
package berack96.lib.graph.view.edge;
import berack96.lib.graph.Vertex;
import berack96.lib.graph.view.GraphPanel;
public class EdgeIntListener<V> extends EdgeListener<V, Integer> {
public EdgeIntListener(GraphPanel<V, Integer> graphPanel) {
super(graphPanel);
}
@Override
public void remove() {}
@Override
protected Integer buildNewEdge(Vertex<V> vertex, Vertex<V> vertex1) {
return (int) (Math.random() * 100);
}
@Override
protected Integer buildEdgeFrom(String string) {
return Integer.parseInt(string.replaceAll("[^0-9]+", ""));
}
}

View File

@@ -0,0 +1,128 @@
package berack96.lib.graph.view.edge;
import berack96.lib.graph.Vertex;
import berack96.lib.graph.view.GraphListener;
import berack96.lib.graph.view.GraphPanel;
import berack96.lib.graph.view.vertex.VertexComponent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.concurrent.atomic.AtomicReference;
public abstract class EdgeListener<V, W extends Number> implements GraphListener {
private final GraphPanel<V, W> graphPanel;
private final AtomicReference<VertexComponent<V>> componentPressed = new AtomicReference<>();
private final AtomicReference<Integer> buttonPressed = new AtomicReference<>();
private final AtomicReference<EdgeComponent<V, W>> edge = new AtomicReference<>();
private final StringBuilder string = new StringBuilder();
public EdgeListener(GraphPanel<V, W> graphPanel) {
this.graphPanel = graphPanel;
}
protected abstract W buildNewEdge(Vertex<V> vertex, Vertex<V> vertex1);
protected abstract W buildEdgeFrom(String string);
@Override
public String getDescription() {
return "<html>"
+ "Modify edges with:<br />"
+ "mouse SX on vertex to another ==> add<br />"
+ "mouse DX on edge ==> change weigth<br />"
+ "(only numbers allowed)"
+ "</html>";
}
@Override
public void mousePressed(MouseEvent e) {
buttonPressed.set(e.getButton());
componentPressed.set(graphPanel.getVertexAt(e.getPoint()));
}
@Override
public void mouseReleased(MouseEvent e) {
try {
edge.get().source.vertex.unMark("modS");
edge.get().destination.vertex.unMark("modD");
edge.set(null);
} catch (Exception ignored) {}
if (buttonPressed.get() == MouseEvent.BUTTON1) {
try {
VertexComponent<V> source = componentPressed.get();
VertexComponent<V> destination = graphPanel.getVertexAt(e.getPoint());
if (!graphPanel.getGraph().containsEdge(source.vertex.getValue(), destination.vertex.getValue())
&& !source.vertex.equals(destination.vertex))
graphPanel.addEdge(source, destination, buildNewEdge(source.vertex, destination.vertex));
} catch (Exception ignore) {
}
} else {
edge.set(graphPanel.getEdgeAt(e.getPoint()));
try {
edge.get().source.vertex.mark("modS");
edge.get().destination.vertex.mark("modD");
graphPanel.setFocusTraversalKeysEnabled(false);
graphPanel.requestFocusInWindow();
} catch (Exception ignored) {}
}
string.delete(0, string.length());
componentPressed.set(null);
graphPanel.repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if (edge.get() != null && Character.isDigit(e.getKeyChar())) {
string.append(e.getKeyChar());
try {
graphPanel.modEdge(edge.get().source, edge.get().destination, buildEdgeFrom(string.toString()));
graphPanel.repaint();
} catch (Exception ignored) {
}
} else {
try {
edge.get().source.vertex.unMark("modS");
edge.get().destination.vertex.unMark("modD");
} catch (Exception ignored) {}
edge.set(null);
string.delete(0, string.length());
}
graphPanel.repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}

View File

@@ -0,0 +1,109 @@
package berack96.lib.graph.view.edge;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.Collection;
import berack96.lib.graph.view.GraphicalView;
import berack96.lib.graph.view.stuff.Arrow;
public class EdgeView<V, W extends Number> implements GraphicalView<EdgeComponent<V, W>> {
private static final Font FONT = new Font("Papyrus", Font.BOLD, 14);
@Override
public Rectangle getBox(EdgeComponent<V, W> edge, Point center) {
/* CALCULATING BOUNDS AND ARROW STARTING AND ENDING POINTS */
Point srcLoc = edge.source.getLocation();
Point desLoc = edge.destination.getLocation();
/* getting the radius */
int srcRadius = edge.source.getHeight() / 2;
int desRadius = edge.destination.getHeight() / 2;
/* centering the location */
srcLoc.translate(srcRadius, srcRadius);
desLoc.translate(desRadius, desRadius);
/* using vector for moving to the edge of the circumference and finding location of int box */
final Point.Double vector = getVector(srcLoc, desLoc);
/* CALCULATING THE NUMBER SPACE */
int boxDistance = (int) (srcLoc.distance(desLoc) / 2.7);
FontMetrics metrics = edge.getFontMetrics(FONT);
int dimString = metrics.stringWidth(edge.weight.toString());
int dimRect = Math.max(dimString, metrics.getHeight());
return new Rectangle(
(int) ((desLoc.x - (vector.x * boxDistance)) - (dimRect / 2)),
(int) ((desLoc.y - (vector.y * boxDistance)) - (dimRect / 2)),
dimRect, dimRect);
}
@Override
public void paint(Graphics2D g2, EdgeComponent<V, W> edge, Point center) {
/* CALCULATING BOUNDS AND ARROW STARTING AND ENDING POINTS */
Point srcLoc = edge.source.getLocation();
Point desLoc = edge.destination.getLocation();
/* getting the radius */
int srcRadius = edge.source.getHeight() / 2;
int desRadius = edge.destination.getHeight() / 2;
/* centering the location */
srcLoc.translate(srcRadius, srcRadius);
desLoc.translate(desRadius, desRadius);
/* using vector for moving to the edge of the circumference and finding location of int box */
final Point.Double vector = getVector(srcLoc, desLoc);
/* CALCULATING THE NUMBER SPACE */
int boxDistance = (int) (srcLoc.distance(desLoc) / 2.7);
FontMetrics metrics = edge.getFontMetrics(FONT);
int dimString = metrics.stringWidth(edge.weight.toString());
int dimRect = Math.max(dimString, metrics.getHeight());
Rectangle integerRect = new Rectangle(
(int) ((desLoc.x - (vector.x * boxDistance)) - (dimRect / 2)),
(int) ((desLoc.y - (vector.y * boxDistance)) - (dimRect / 2)),
dimRect, dimRect);
/* moving to a distance R to the center */
srcLoc.translate((int) (vector.x * srcRadius), (int) (vector.y * srcRadius));
desLoc.translate((int) (-vector.x * desRadius), (int) (-vector.y * desRadius));
/* THE COLOR OF THE ARROW */
Collection<Object> marksD = edge.destination.vertex.getMarks();
Collection<Object> marksS = edge.source.vertex.getMarks();
boolean isChild = marksD.contains(edge.source.vertex.getValue());
boolean selected = marksS.contains("selected");
boolean isMod = marksD.contains("modD") && marksS.contains("modS");
Color arrowColor = isChild || selected ? Color.RED : Color.BLACK;
Color boxColor = isChild || selected || isMod ? Color.ORANGE : Color.BLUE;
Color stringColor = isChild || selected || isMod ? Color.BLACK : Color.CYAN;
g2.setFont(FONT);
/* draw all */
g2.setColor(arrowColor);
//g2d.drawLine(arrowStart.x, arrowStart.y, arrowEnd.x, arrowEnd.y);
Polygon arrow = new Arrow(srcLoc, desLoc, 1, 10);
//g2d.draw(arrow);
g2.fillPolygon(arrow);
/* draw the integer space */
g2.setColor(boxColor);
g2.fill(integerRect);
g2.setColor(arrowColor);
g2.draw(integerRect);
g2.setColor(stringColor);
g2.drawString(edge.weight.toString(), (float) (integerRect.x + (dimRect - dimString) / 2), (float) (integerRect.y + (dimRect + metrics.getHeight() / 2) / 2));
}
private Point.Double getVector(Point a, Point b) {
final Point.Double vector = new Point2D.Double(b.x - a.x, b.y - a.y);
/* normalizing vector */
double length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
if(length != 0) {
vector.x = vector.x / length;
vector.y = vector.y / length;
}
return vector;
}
}

View File

@@ -0,0 +1,59 @@
package berack96.lib.graph.view.stuff;
import java.awt.*;
/**
* Class that create a Polygon that has a shape of an arrow
*
* @author Berack96
*/
public class Arrow extends Polygon {
private static final long serialVersionUID = 1L;
/**
* Create an arrow
*
* @param start the starting point of your arrow (the base)
* @param end the ending point of your arrow (the head)
* @param size the size of the arrow base
* @param headSize the size of the arrow's head
*/
public Arrow(Point start, Point end, final int size, final int headSize) {
final Point.Double vector = new Point.Double(end.x - start.x, end.y - start.y);
/* vectors normalization */
double length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
vector.x = vector.x / length;
vector.y = vector.y / length;
final Point headStart = new Point((int) (end.x - vector.x * headSize), (int) (end.y - vector.y * headSize));
/* rotating vector for the parallels */
double cs = Math.cos(Math.PI / 2);
double sn = Math.sin(Math.PI / 2);
double x = vector.x * cs - vector.y * sn;
double y = vector.x * sn + vector.y * cs;
vector.setLocation(x, y);
/* TODO here use some magic for create a curve arrow if vector.x == vector.y && vector.x == 0 */
/* building arrow starting from A to G */
/*
C
|\
| \
A--------B \
| D
G--------F /
| /
|/
E
*/
addPoint((int) (start.x - vector.x * size), (int) (start.y - vector.y * size));
addPoint((int) (start.x + vector.x * size), (int) (start.y + vector.y * size));
addPoint((int) (headStart.x + vector.x * size), (int) (headStart.y + vector.y * size));
addPoint((int) (headStart.x + vector.x * headSize), (int) (headStart.y + vector.y * headSize));
addPoint(end.x, end.y);
addPoint((int) (headStart.x - vector.x * headSize), (int) (headStart.y - vector.y * headSize));
addPoint((int) (headStart.x - vector.x * size), (int) (headStart.y - vector.y * size));
}
}

View File

@@ -0,0 +1,31 @@
package berack96.lib.graph.view.vertex;
import java.awt.*;
import berack96.lib.graph.Vertex;
public class VertexComponent<V> extends Component {
private static final long serialVersionUID = 1L;
public final Vertex<V> vertex;
public VertexComponent(Vertex<V> vertex) {
this.vertex = vertex;
}
@Override
public String toString() {
return "[" + vertex + " {" + getX() + "," + getY() + "}]";
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
try {
return obj.getClass().equals(getClass()) && ((VertexComponent<V>)obj).vertex.equals(vertex);
} catch (Exception e) {
return false;
}
}
}

View File

@@ -0,0 +1,30 @@
package berack96.lib.graph.view.vertex;
import java.util.Arrays;
import berack96.lib.graph.Graph;
import berack96.lib.graph.view.GraphPanel;
public class VertexIntListener extends VertexListener<Integer> {
public VertexIntListener(GraphPanel<Integer, ?> panel) {
super(panel);
}
@Override
public void remove() {}
@Override
protected Integer buildNewVertex(Graph<Integer, ?> graph) {
int counter = 0;
Integer[] vertices = graph.vertices().toArray(new Integer[graph.numberOfVertices()]);
Arrays.sort(vertices);
for(int i = 0; i<vertices.length; i++) {
if(!vertices[i].equals(counter))
return counter;
counter++;
}
return counter;
}
}

View File

@@ -0,0 +1,91 @@
package berack96.lib.graph.view.vertex;
import berack96.lib.graph.Graph;
import berack96.lib.graph.view.GraphListener;
import berack96.lib.graph.view.GraphPanel;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.concurrent.atomic.AtomicReference;
public abstract class VertexListener<V> implements GraphListener {
protected final GraphPanel<V, ?> panel;
private final AtomicReference<VertexComponent<V>> componentPressed = new AtomicReference<>();
public VertexListener(GraphPanel<V, ?> panel) {
this.panel = panel;
}
protected abstract V buildNewVertex(Graph<V, ?> graph);
@Override
public String getDescription() {
return "<html>"
+ "Modify vertex with:<br />"
+ "mouse SX ==> add<br />"
+ "mouse SX on vertex ==> move<br />"
+ "mouse DX ==> remove<br />"
+ "</html>";
}
@Override
public void mousePressed(MouseEvent e) {
try {
if (e.getButton() == MouseEvent.BUTTON1)
componentPressed.set(panel.getVertexAt(e.getPoint()));
} catch (Exception ignore) {}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && componentPressed.get() == null)
panel.addVertex(e.getPoint(), buildNewVertex(panel.getGraph()));
else if (e.getButton() == MouseEvent.BUTTON3)
panel.removeVertex(e.getPoint());
panel.getGraph().unMarkAll("selected");
if(componentPressed.get() != null)
componentPressed.get().vertex.mark("selected");
panel.repaint();
componentPressed.set(null);
}
@Override
public void mouseDragged(MouseEvent e) {
if (componentPressed.get() != null) {
panel.moveVertex(componentPressed.get(), e.getPoint());
panel.repaint();
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}

View File

@@ -0,0 +1,42 @@
package berack96.lib.graph.view.vertex;
import java.awt.*;
import berack96.lib.graph.view.GraphicalView;
public class VertexView<V> implements GraphicalView<VertexComponent<V>> {
private static final Font FONT = new Font("Comic Sans MS", Font.BOLD, 17);
private static final int PADDING = 6;
@Override
public Rectangle getBox(VertexComponent<V> obj, Point center) {
FontMetrics metrics = obj.getFontMetrics(FONT);
int stringPixels = metrics.stringWidth(obj.vertex.getValue().toString());
int size = Math.max(stringPixels, metrics.getHeight()) + 2 * PADDING;
return new Rectangle(center.x - size / 2, center.y - size / 2, size, size);
}
@Override
public void paint(Graphics2D g2, VertexComponent<V> obj, Point center) {
boolean discovered = obj.vertex.getMarks().contains("discovered");
boolean visited = obj.vertex.getMarks().contains("visited");
boolean selected = obj.vertex.getMarks().contains("selected");
FontMetrics metrics = obj.getFontMetrics(FONT);
int stringPixels = metrics.stringWidth(obj.vertex.getValue().toString());
int size = Math.max(stringPixels, metrics.getHeight()) + 2 * PADDING;
center.x = center.x - size / 2;
center.y = center.y - size / 2;
g2.setFont(FONT);
g2.setColor(visited || selected ? Color.RED : Color.ORANGE);
g2.fillOval(center.x, center.y, size, size);
g2.setColor(visited || discovered || selected ? Color.ORANGE : Color.YELLOW);
g2.fillOval(center.x + PADDING / 2, center.y + PADDING / 2, size - PADDING, size - PADDING);
g2.setColor(Color.BLACK);
g2.drawString(obj.vertex.getValue().toString(), center.x + PADDING + (size - 2 * PADDING - stringPixels) / 2, center.y + (size) / 2 + PADDING);
}
}