i having problem changing shapes displayed when user clicks on menu item in java using jframe. can suggest how can solve this? below code:
public class playingwithshapes implements actionlistener { protected jmenuitem circle = new jmenuitem("circle"); protected string identifier = "circle"; public playingwithshapes() { jmenubar menubar = new jmenubar(); jmenu shapes = new jmenu("shapes"); jmenu colors = new jmenu("colors"); circle.addactionlistener(this); shapes.add(circle); menubar.add(shapes); menubar.add(colors); jframe frame = new jframe("playing shapes"); frame.setsize(600,400); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); frame.add(new shapes()); frame.setjmenubar(menubar); } public static void main(string args[]) { runnable runnable = new runnable() { @override public void run() { new playingwithshapes(); } }; eventqueue.invokelater(runnable); }
i want change shape circle when clicking on circle menuitem
@override public void actionperformed(actionevent click) { if(click.getsource() == circle){ shapes shape = new shapes(); } } public class shapes extends jpanel {
how can call rectangle?
@override public void paintcomponent(graphics shapes) { circle(shapes); } public void circle(graphics shapes) { shapes.setcolor(color.yellow); shapes.filloval(200,100, 100, 100); } public void rectangle(graphics shapes) { shapes.setcolor(color.magenta); shapes.fillrect(200,100,100,100); } } }
any appreciated.
suggestions:
- don't create new shapes jpanel within actionperformed achieves nothing.
- instead within actionperformed change state of field of class, , base drawing within paintcomponent method on state held field.
- for instance, if have 2 different types of shapes, above field boolean, perhaps called
drawrectangle
, , in actionperformed you'd change true or false , callrepaint();
. , in you'd use if block within paintcomponent drawing rectangle if true or oval if not. - if want have ability draw multiple different shapes, create enum , make field discussed above field of enum type. use switch statement within paintcomponent decide shape draw.
- if want show different shapes @ same time, you'll need create collection of shape such
arraylist<shape>
, add shape-derived objects collection, , iterate through in loop within paintcomponent using graphics2d object draw each shape. don't think need right now. - don't forget call
super.paintcomponent(g);
within method override.
i.e.,
@override public void paintcomponent(graphics g) { super.paintcomponent(g); if (drawrectangle) { rectangle(g); } else { circle(g); } }
Comments
Post a Comment