java - Drawing and storing objects by clicking the mouse button -
java - Drawing and storing objects by clicking the mouse button -
i trying draw circle objects each click , store every circle object arraylist, don't know why programme not working! if removed arraylist , line create new circle object, programme work. how create programme store circuit objects arraylist ?
import javax.swing.jpanel; import java.awt.color; import java.awt.graphics; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import java.util.arraylist; import java.util.random; public class circleobj extends jpanel { private int rcolor; private int gcolor; private int bcolor; private int radius; private random rand = new random(); private int xstart; private int ystart; arraylist <circle> xxx ; public circleobj () { xxx = new arraylist<circle>(); addmouselistener(new mouseadapter() { public void mouseclicked (mouseevent e) { xstart = e.getx(); ystart = e.gety(); rcolor = rand.nextint(256); gcolor = rand.nextint(256); bcolor = rand.nextint(256); radius = rand.nextint(20); repaint(); } }); // end addmouselistener } public void paintcomponent (graphics g) { super.paintcomponent(g); g.setcolor(new color(rcolor, gcolor, bcolor)); g.filloval(xstart, ystart, radius, radius); xxx.add(new circle()); } private class circle { private int x; private int y; private int r; private int rcol; private int gcol; private int bcol; public circle() { x=xstart; y=ystart; r=radius; rcol= rcolor; gcol= gcolor; bcol= bcolor; } } }
======
import javax.swing.jframe; import java.awt.borderlayout; public class hw3 { public static void main (string[] arg) { jframe frame = new jframe("circles"); circleobj canvas = new circleobj(); frame.add(canvas, borderlayout.center); frame.setbounds(250, 98, 600, 480); //frame.setlayout(new borderlayout()); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); } // end main } //end hw3
don't add together new shape within paintcomponent
method, paintcomponent
can called number of reasons, many of don't control, instead, create when mouseclicked
event triggered...
public void mouseclicked (mouseevent e) { xstart = e.getx(); ystart = e.gety(); rcolor = rand.nextint(256); gcolor = rand.nextint(256); bcolor = rand.nextint(256); radius = rand.nextint(20); xxx.add(new circle(xstart, ystart, new color(rcolor, gcolor, bcolor), radius)); repaint(); }
and in paintcomponent
, loop through arraylist
, paint circles...
public void paintcomponent (graphics g) { super.paintcomponent(g); (circle c : xxx) { g.setcolor(c.getcolor()); g.filloval(c.getx(), c.gety(), c.getradius(), c.getradius()); } }
now, you're going have modify circle
class provide getters circleobj
can utilize in order paint circles...
alternatively, create utilize of shape
s api provided within java...have @ working geometry more details...
java swing draw
Comments
Post a Comment