The button is firing the event, but it is not showing. It creates new circles, but it doesn’t draw the new circles. Is there something I’m not doing? (first java applet). It’s probably something stupid I’m missing..
import java.applet.*;
public class CircleApp extends Applet {
public circle[] circles;
public Button regen;
public CircleApp(){
}
public void init()
{
this.setSize(400, 400);
genCircles(getWidth(), getHeight());
regen = new Button("New Circles");
add(regen);
}
public boolean action(Event e, Object args)
{
genCircles(getWidth(), getHeight());
return true;
}
public void genCircles(int wid, int hei)
{
circles = new circle[20];
Random gen = new Random();
for (int i = 0; i < 20; i++)
{
int x = gen.nextInt(wid);
int y = gen.nextInt(hei);
int rx = Math.min(x, wid - x);
int ry = Math.min(y, hei - y);
int r = Math.min(rx, ry);
circles[i] = new circle(new Point(x, y), gen.nextInt(r));
}
for (int i = 0; i < 20; i++)
{
for (int j = i; j < 20; j++)
{
if (circles[i].intersects(circles[j]))
{
circles[i].intersects = true;
break;
}
}
}
}
public void paint(Graphics g)
{
for (int i = 0; i < 20; i++)
{
g.setColor((circles[i].intersects) ? Color.blue : Color.magenta);
g.drawOval(circles[i].location.x,
circles[i].location.y,
circles[i].radius,
circles[i].radius);
}
}
}
import java.awt.Point;
public class circle {
public Point location;
public int radius;
public boolean intersects;
public circle(Point h, int radius)
{
this.location = h;
this.radius = radius;
}
public circle()
{
this(new Point(0, 0), 1);
}
public boolean intersects(circle other)
{
return (this.location.distance(other.location) <
(double)(this.radius + other.radius));
}
}
Thanks for the help!!
You need to call
repaint()to redraw the new circles after you generate them.Also, not directly related to your question, but
action()is deprecated — use an action listener on the button instead.