java - Graphics in an ArrayList -
i trying create code prints 10 random graphics (oval,rectangle etc). i'm hopping adding random ovals etc in arraylist , let java randomly pick shape 10 times arraylist , print these picked items.
now have no idea if possible , how go this.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class cara extends jpanel implements actionlistener { random random = new random(); //...s public cara() { setpreferredsize(new dimension(400,300)); // make panel 400 300 pixels. // ... this.setbackground(color.white); } protected class randomshapescomponent extends jcomponent{ @override protected void paintcomponent(graphics g) { super.paintcomponent(g); // clears background // ... } } /** * redraws cara jpanel, when button pressed. * */ @override public void actionperformed(actionevent e) { regenerate(); repaint(); } private void regenerate() { // clear shapes list //... // create random shapes // ... } public static void main(string[] arg) { final cara cara = new cara(); // create gui on event thread. // better swingutilities.invokelater(new runnable() { @override public void run() { final jframe frame = new jframe("computer assisted random artist"); frame.add(cara, borderlayout.center); jbutton button = new jbutton("redraw"); button.addactionlistener(cara); frame.add(button, borderlayout.south); frame.pack(); cara.regenerate(); // can done here if cara has size! frame.setvisible(true); } }); } }
and below way me draw triangle (this 1 of shapes put array , randomly picked):
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class tri extends cara{ public void paintcomponent (graphics g){ // create random variables collor , shape of triangle int x; int y; int x2; int y2; x = (int) math.random()*100; y = (int) math.random()*100; x2 = (int) math.random()*100; y2 = (int) math.random()*100; int r1; int g1; int b1; r1 = (int) math.random()*255; g1 = (int) math.random()*255; b1 = (int) math.random()*255; color color = new color(r1,g1,b1); //draw triangle g.setcolor(color); g.drawline(x,y,y2,y); g.setcolor(color); g.drawline(x,y,y2,y2); g.setcolor(color); g.drawline(y2,y,y2,y2); } }
this possible. here's idea:
- have abstract base class called "shape" , has method called "draw()" has parameter graphics context
- have subclasses of shape triangle, circle, etc , fill in each's draw() method accordingly
- have arraylist instance variable in fruitpanel
- in fruitpanel constructor initialize arraylist 10 shape subclass objects
- from paintcomponent() method in fruitpanel call draw(g) on each of things in arraylist
you can figure out randomization , such yourself... basic structure. luck!
Comments
Post a Comment