java - Moving objects in Jframe -
i've got kind of jbutton want move, example in code:
package javaapplication19; import java.awt.*; import java.awt.container; import java.awt.event.*; import javax.swing.*; import javax.swing.jframe; public class javaapplication19 extends jframe{ public static jbutton button=new jbutton("button");//button move public static int x; public static int y; public javaapplication19(){ final container c = getcontentpane(); c.setlayout(null); button.setbounds(100,100,100,100); c.add(button); //mouselistenerstart button.addmouselistener(new mouseadapter() { public void mousepressed(mouseevent e) { if(!e.ismetadown()){ x = e.getx(); y = e.gety(); } } }); button.addmousemotionlistener(new mousemotionadapter() { public void mousedragged(mouseevent e) { if(!e.ismetadown()){ point p = getlocation(); button.setlocation(p.x + e.getx() - x, p.y + e.gety() - y); } } }); //mouselistenerend } public static void main(string[] args) { javaapplication19 marco=new javaapplication19 (); marco.setsize(1000,700); marco.setvisible(true); marco.setdefaultcloseoperation(jframe.exit_on_close); }}
but there 2 problems. first 1 jbutton moves slower mouse. second 1 jbutton seems jump between 2 places in jframe when dragging it.
how solve these problems?
solved.
in code:
package javaapplication19; import java.awt.*; import java.awt.container; import java.awt.event.*; import javax.swing.*; import javax.swing.jframe; public class javaapplication19 extends jframe{ public static jbutton button=new jbutton("button");//button move public static int x; public static int y; public javaapplication19(){ final container c = getcontentpane(); c.setlayout(null); button.setbounds(100,100,100,100); c.add(button); //mouselistenerstart button.addmouselistener(new mouseadapter() { public void mousepressed(mouseevent e) { if(!e.ismetadown()){ x = e.getx(); y = e.gety(); } } }); button.addmousemotionlistener(new mousemotionadapter() { public void mousedragged(mouseevent e) { if(!e.ismetadown()){ point p = button.getlocation();\\i had put button.getlocation() instead of getlocation() button.setlocation(p.x + e.getx() - x, p.y + e.gety() - y); } } }); //mouselistenerend } public static void main(string[] args) { javaapplication19 marco=new javaapplication19 (); marco.setsize(1000,700); marco.setvisible(true); marco.setdefaultcloseoperation(jframe.exit_on_close); } }
Comments
Post a Comment