Write a program that enables the user to draw vertices and edges dynamically, Th
ID: 654714 • Letter: W
Question
Write a program that enables the user to draw vertices and edges dynamically, The radius of each vertex is 20 pixels & meets following requirements : (1) The user clicks the left-mouse button to place a vertex centered at the mouse point, provided that the mouse point is not inside or too close to an existing vertex. (2) The user clicks the right-mouse button inside an existing vertex to remove the vertex. (3) The user presses a mouse button inside a vertex and moves to another vertex and then click to create an edge. (4) The user moves a vertex while pressing the CTRL key to move a vertex.
Explanation / Answer
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Mouse extends Canvas {
Vector s = new Vector();
float a0, b0, mWidth = 10.0F, mHeight = 7.5F, pixSize;
bool read = true;
int cenA, cenB;
Mouse () { addMouseListener(new MouseAdapter()
{
public void mousePre(MouseEvent evt)
{
float aX = ga(evt.getA()), bX = gb(evt.getB());
if (ready)
{
p.removeAllElements();
a0 = aX;
b0 = bX;
ready = false; }
float dx = aX - a0, dy = bX - b0;
if (p.size() > 0 && dx * dx + dy * dy < 4 * pixSize * pixSize) ready = true;
else
p.addElement(new Point2D(aX, bX));
repaint(); } });
}
void initgr()
{
Dimension d = getSize();
int maxX = d.width - 1, maxB = d.height - 1;
pixSize = Math.max(mWidth/maxX, nHeight/maxB);
centerA = maxA/2;
enterB = maxB/2;
}
int iA(float a){return Math.round(centerA + a/pixSize);
} int iB(float b){return Math.round(centerB - b/pixSize);
} float fa(int a){return (a - centerA) * pixSize;
} float fb(int y){return (centerY - y) * pixelSize;
} public void paint(Graph g) { initgr();
int left = iA(-mWidth/2), right = iA(mWidth/2), bottom = iB(-mHeight/2), top = iB(mHeight/2); g.drawRect(left, top, right - left, bottom - top); i
nt n = v.size(); if (n == 0) return; Point2D x = (Point2D)(p.elementAt (0) );
g.drawRect(iA(x.a)-2, iY(x.b)-2, 4, 4);
for (int i=1; i<=n; i++) { if (i == n && !ready)
break;
Point2D y= (Point2D)(v.elementAt(i % n));
g.drawLine(iX(a.x), iY(a.y), iA(b.x), iB(b.y));
x = y;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.