java - drawing an oval after clicking the mouse -


i want draw oval when click mouse in panel. , drawing allowed after click button. problem occurs: copy of button drawn in top left of panel.

this code:

 public class paintpanel extends jpanel implements mouselistener, mousemotionlistener{          private boolean draw = false;         private jbutton button;         private point mypoint;         public paintpanel(){             this.setsize(800,600);             button = new jbutton("allow draw");             button.setsize(30,30);             this.add(button);             this.addmouselistener(this);             this.addmousemotionlistener(this);             button.addactionlistener(new actionlistener() {                  @override                 public void actionperformed(actionevent arg0) {                     draw = true;                  }             });         }         @override         public void paintcomponent(graphics g){             g.setfont(new font("arial",font.bold,24));             g.setcolor(color.blue);             if(draw){                 g.drawoval(mypoint.x-10, mypoint.y-10, 20, 20);             }         }         @override         public void mousepressed(mouseevent e) {             if(draw){                 mypoint = e.getpoint();                 repaint();             }         }         public static void main(string[] agrs){             jframe frame = new jframe("painting on panel");             frame.add(new paintpanel());             frame.setvisible(true);             frame.setsize(800,600);             frame.setdefaultcloseoperation(jframe.exit_on_close);             frame.setlocationrelativeto(null);         }     } 

you broke paint chain.

add super.paintcomponent(g) before custom painting

public void paintcomponent(graphics g){     super.paintcomponent(g);     g.setfont(new font("arial",font.bold,24));     g.setcolor(color.blue);     if(draw){         g.drawoval(mypoint.x-10, mypoint.y-10, 20, 20);     } } 

graphics shared resource. provided painted within given paint cycle, meaning, unless clear first, contain other things have been painted before you.

one of jobs of paintcomponent prepare graphics context painting, clearing (filling components background color)

take closer @ performing custom painting , painting in awt , swing more details


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -