import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; public class GraphView extends JFrame implements MouseListener { private double edge[][]; private double x[], y[]; private int SIZE; private final int WIDTH = 450; private final int HEIGHT = 450; private final int MARGIN = 200; public void update(Graphics g) { paint(g); } public void makeLoop() { for(int i = 0; i < SIZE-1; i++) { edge[i][i+1] = 1; edge[i+1][i] = 1; } edge[0][SIZE-1] = 1; edge[SIZE-1][0] = 1; if (Math.random() > 0.5) { edge[0][SIZE/2] = 1; edge[SIZE/2][0] = 1; } } public void randomEdge() { for(int i = 0; i < SIZE; i++) { for(int j = 0; j < SIZE; j++) if (Math.random() < 1.0/SIZE) { edge[i][j] = 1; edge[j][i] = 1; }} } public GraphView() { addMouseListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we) { System.exit(0);} }); setSize(HEIGHT+MARGIN,WIDTH+MARGIN); SIZE = 100; // (int)(Math.random() * 123)+1; edge = new double[SIZE][SIZE]; x = new double[SIZE]; y = new double[SIZE]; // create random locations for nodes for (int k = 0; k < SIZE; k++) { x[k] = Math.random(); y[k] = Math.random(); } if (Math.random() > 0.5) randomEdge(); else makeLoop(); show(); } public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0,0,WIDTH+MARGIN, HEIGHT+MARGIN); g.setColor(Color.black); double maxX = x[0], maxY = y[0], minX = x[0], minY = y[0]; for(int i = 0; i < SIZE; i++) { if (x[i] > maxX) maxX = x[i]; if (x[i] < minX) minX = x[i]; if (y[i] > maxY) maxY = y[i]; if (y[i] < minY) minY = y[i]; } for(int i = 0; i < SIZE; i++) { int newX = (int)(WIDTH * (x[i] - minX))+(MARGIN/2); int newY = (int)(HEIGHT * (y[i] - minY))+(MARGIN/2); g.setColor(new Color(i*255/SIZE, 0, 255-i*255/SIZE)); g.fillOval(newX, newY,20,20); for(int j = 0; j < SIZE; j++) { if (edge[i][j] != 0) { int newX2 = (int)(WIDTH*(x[j] - minX))+(MARGIN/2); int newY2 = (int)(HEIGHT*(y[j] - minY))+(MARGIN/2); g.drawLine(newX+10, newY+10, newX2+10, newY2+10); }} g.setColor(Color.white); g.drawString(""+ (i+1), newX+3, newY + 15); }} public void ChangeGraph() { int i, j; // add edge do { i = (int)(Math.random() * SIZE); j = (int)(Math.random() * SIZE); } while (i == j || edge[i][j] != 0); edge[i][j] = 1; edge[j][i] = 1; // remove edge while(true) { i = (int)(Math.random() * SIZE); j = (int)(Math.random() * SIZE); if (edge[i][j] != 0) { edge[i][j] = 0; edge[j][i] = 0; return; } } } public void addEdge(){ int i, j; // add edge do { i = (int)(Math.random() * SIZE); j = (int)(Math.random() * SIZE); } while (i == j || edge[i][j] != 0); edge[i][j] = 1; edge[j][i] = 1; } public void mouseClicked(MouseEvent me) { ChangeGraph(); repaint(); } public void mouseExited(MouseEvent me) {} public void mouseEntered(MouseEvent me) { addEdge(); repaint(); } public void mouseReleased(MouseEvent me) {} public void mousePressed(MouseEvent me) {} public static void main(java.lang.String[] args) { new GraphView(); } }