java - Label gets added to JPanel without reason swing -
i'm trying make simple application painting. have main method sets jframe, , adds jpanel , jlabel using flowlayout. jlabel counting clicks.
the panel class implements mouselistener , mousemotionlistener.
the problem when paint or click on panel, adds label jpanel aswell, , depending on click, can add twice panel, it's making me mad. can't understand why it's added jpanel.
also, jpanel surrounded border, , when click or paint adds new vertical borderline somewhere on panel, it's random every time.
code 2 classes:
public class mainepanel extends jpanel implements mousemotionlistener, mouselistener{ graphics globalgraphics; int clickcount = 0; public mainepanel(){ setborder(borderfactory.createlineborder(color.black)); setpreferredsize(new dimensionuiresource(200,200)); addmousemotionlistener(this); addmouselistener(this); validate(); setfocusable(true); } public void paintcomponent(graphics g){ globalgraphics = g.create(); } @override public void mousedragged(mouseevent e) { globalgraphics.filloval(e.getx(), e.gety(), 10,10); repaint(); } @override public void mouseclicked(mouseevent e) { clickcount ++; maine.setlabel(clickcount); globalgraphics.filloval(e.getx(), e.gety(), 10,10); repaint(); }
maine
public class maine extends jframe{ static jlabel label; public maine(){ setsize(600,400); setdefaultcloseoperation(3); setresizable(false); label = new jlabel("clicks:"); setlayout(new flowlayout()); add(label); add(new mainepanel()); setvisible(true); } public static void setlabel(int clicks){ label.settext("clicks: " + clicks); } public static void main(string[]args){ new maine(); } }
perform drawing within paintcomponent
(and sure call super.paintcomponent
) - mouselistener
/mousemotionlistener
should need change data model (and if necessary call repaint
ui reflects change).
a simple example below single circle created mouse click, , moved mouse dragged:
point center = null; ... @override public void mouseclicked(mouseevent e){ center = e.getpoint(); repaint(); } @override public void mousedragged(mouseevent e){ center = e.getpoint(); repaint(); } @override protected void paintcomponent(graphics g){ super.paintcomponent(g); if ( center != null ){ g.filloval(center.getx(), center.gety(), 10, 10); } }
Comments
Post a Comment