java - Dragging BufferedImage in JPanel -
i have jpanel inside jframe , there more 1 bufferedimages in jpanel this.
now question how can move bufferedimages inside jpanel? more how add mouseeventhandler buffered images?. though can drag jpanel code below can't figure out how drag buffered images inside jpanel. help.
i have 3 classes this
mainwindow.java
public class mainwindow extends jframe { public static void main(string[] args) { eventqueue.invokelater(new runnable() { public void run() { try { mainwindow window = new mainwindow(); window.frame.setvisible(true); } catch (exception e) { } } }); } public mainwindow() { jframe frame = new jframe(); .... // other code of jframe jpanel panel_3 = new jpanel(); .... // other code of jpanel frame.getcontentpane().add(panel_3); panel_3.setlayout(new borderlayout(0, 0)); drawing drawingobj = new drawing(); panel_3.removeall(); panel_3.add(drawingobj ); drawingobj .revalidate(); drawingobj .repaint(); basicdragging drag= new basicdragging(); panel_3.addmouselistener(drag); panel_3.addmousemotionlistener(drag); } }
drawing.java
public class drawing extends jpanel { private bufferedimage image1 ; private bufferedimage image2; private bufferedimage image3; public drawing() { try { image1 = imageio.read(new file("path of file")); image2 = imageio.read(new file("path of file")); image3 = imageio.read(new file("path of file")); } catch (ioexception ex) { // handle exception... } @override protected void paintcomponent(graphics g) { super.paintcomponent(g); g.drawimage(image1 , 150, 10, null); g.drawimage(image2 , 150, 70,null); // other code of drawing images } } }
basicdragging.java
public class basicdragging extends mouseinputadapter{ point location; mouseevent pressed; public void mousepressed(mouseevent me) { pressed = me; } public void mousedragged(mouseevent me) { component component = me.getcomponent(); location = component.getlocation(location); int x = location.x - pressed.getx() + me.getx(); int y = location.y - pressed.gety() + me.gety(); component.setlocation(x, y); } }
my first suggestion simple one...
as can see draw these images coordinates, x , y. add mouselistener jpanel. that's magic happens , rather confusing if create more objects.
now have check if mouse hover above image , pressed. need calculate size , if point inside image. if inside image moves in direction of mouse. , shouldn't reset position rather move along. that's how done. set x , y images when clicked , pressed on.
i'd create object dragimage contains core bufferedimage + coordinates represent x , y , it's size. additionally i'd add function calculates public boolean ishovering(int x, int y). should work out. , x , y coordinates used in draw function.
i hope understand trying say
Comments
Post a Comment