/* * Created on 19/06/2003 */ package graph; import java.util.*; import javax.swing.table.AbstractTableModel; /** * @author André Santanchè */ public class GraphTable extends AbstractTableModel { private final String columnName[] = {"Vértice", "Arestas"}; private String tEdges[]; private Vertex vVertex[]; private Hashtable hVertex; public GraphTable(String textVertex[]) { super(); parseVertex(textVertex); tEdges = new String[textVertex.length]; } public GraphTable(String textVertex[], String textEdges[]) { super(); parseVertex(textVertex); this.tEdges = textEdges; parseEdges(); } public GraphTable(Graph g) { super(); parseGraph(g); } public int getRowCount() { return vVertex.length; } public int getColumnCount() { return 2; } public String getColumnName(int coluna) { return columnName[coluna]; } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) return vVertex[rowIndex].getLabel(); else return (tEdges[rowIndex] == null)?"":tEdges[rowIndex]; } public void setValueAt(Object value, int rowIndex, int columnIndex) { String v = (String)value; if (columnIndex == 0 && !v.equals(vVertex[rowIndex].getLabel())) { hVertex.remove(vVertex[rowIndex].getLabel()); vVertex[rowIndex].setLabel(v); hVertex.put(v, vVertex[rowIndex]); } else if (columnIndex == 1 && (tEdges[rowIndex] == null || !v.equals(tEdges[rowIndex]))) { tEdges[rowIndex] = v; parseEdges(); } } public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } public Graph getGraph() { return new Graph(vVertex); } private void parseVertex(String textVertex[]) { vVertex = new Vertex[textVertex.length]; hVertex = new Hashtable(); for (int i=0; i < textVertex.length; i++) { vVertex[i] = new Vertex(textVertex[i]); hVertex.put(textVertex[i], vVertex[i]); } } private void parseEdges() { for (int i = 0; i < tEdges.length; i++) { if (tEdges[i] != null && tEdges[i].length() > 0) { StringTokenizer st = new StringTokenizer(tEdges[i], " ,;\t"); int t = st.countTokens(); if (t > 1) { Vector ve = new Vector(t); for (int j = 0; j < t; j += 2) { String e = st.nextToken(); Vertex vd = (Vertex)hVertex.get(e); e = st.nextToken(); int weight = (e == null) ? 0 : Integer.parseInt(e); ve.addElement(new Edge(vVertex[i], vd, weight)); } vVertex[i].setEdges((Edge[])ve.toArray(new Edge[0])); } } } } private void parseGraph(Graph g) { hVertex = new Hashtable(); vVertex = g.getVertexList(); tEdges = new String[vVertex.length]; for (int i = 0; i < vVertex.length; i++) { hVertex.put(vVertex[i].getLabel(), vVertex[i]); Edge e[] = vVertex[i].getEdges(); if (e != null && e.length > 0) { tEdges[i] = e[0].getDestination().getLabel() + ", " + e[0].getWeight(); for (int j = 1; j < e.length; j++) tEdges[i] += "; " + e[j].getDestination().getLabel() + ", " + e[j].getWeight(); } } } }