-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path70_DragAndDrop
More file actions
73 lines (59 loc) · 1.9 KB
/
70_DragAndDrop
File metadata and controls
73 lines (59 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<Main.java>
public class Main {
public static void main(String[] args){
MyFram myFram = new MyFram();
}
}
<MyFram.java>
import javax.swing.*;
public class MyFram extends JFrame {
DragPanel dragPanel = new DragPanel();
MyFram(){
this.add(dragPanel);
this.setTitle("Drag & Drop demo");
this.setSize(600,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
<DragPanel.java>
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class DragPanel extends JPanel {
ImageIcon image = new ImageIcon("smiley.png");
final int WIDTH = image.getIconWidth();
final int HEIGHT = image.getIconHeight();
Point imageCorner;
Point prevPt;
DragPanel() {
imageCorner = new Point(0, 0);
ClickListener clickListener = new ClickListener();
DragListener dragListener = new DragListener();
this.addMouseListener(clickListener);
this.addMouseMotionListener(dragListener);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
image.paintIcon(this, g, (int) imageCorner.getX(), (int) imageCorner.getY());
}
//Create 2 inner class
private class ClickListener extends MouseAdapter {//wait until we click the mouse
public void mousePressed(MouseEvent e) {
prevPt = e.getPoint();
}
}
private class DragListener extends MouseMotionAdapter {//move image as we move mouse around
public void mouseDragged(MouseEvent e){
Point currentPt = e.getPoint();
imageCorner.translate(
(int)(currentPt.getX()-prevPt.getX()),
(int)(currentPt.getY()-prevPt.getY())
);
prevPt = currentPt;
repaint();
}
}
}