1
19
20 package jguitest;
21
22 import com.imagero.gui.swing.ImagePanel;
23 import com.imagero.gui.swing.MScrollPane;
24
25 import javax.swing.*;
26 import javax.swing.event.MouseInputAdapter;
27 import java.awt.*;
28 import java.awt.event.MouseEvent;
29 import java.net.URL;
30 import java.net.MalformedURLException;
31
32 public class ImagePanelTest extends JApplet {
33
34 public void init() {
35 final Stroke[] strokes = new Stroke[10];
36 for (int i = 0; i < strokes.length; i++) {
37 strokes[i] = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1, new float[]{5, 5}, i);
38 }
39
40 URL url = null;
41 try {
42 url = new URL("http://jgui.imagero.com/examples/classes/jguitest/IMG_0232_lapalma_medium.jpg");
43 }
44 catch (MalformedURLException ex) {
45 ex.printStackTrace();
46 return;
47 }
48 finally {
49 System.err.println(url);
50 }
51
52 Image img = Toolkit.getDefaultToolkit().createImage(url);
53 new ImageIcon(img);
54
55 final ImagePanel ip = new ImagePanel(img);
56
57 final MouseHandler handler = new MouseHandler(ip, strokes);
58 ip.addMouseMotionListener(handler);
59 ip.addMouseListener(handler);
60
61 ip.setAlpha(0.5f);
62 getContentPane().add(new MScrollPane(ip));
63 }
64
65
68 private static class MouseHandler extends MouseInputAdapter {
69 int x, y;
70
71 private final ImagePanel ip;
72 private final Stroke[] strokes;
73
74 int mouseX = 0, mouseY = 0;
75 int index = 0;
76
77 boolean shouldErase;
78
79
80 public void mousePressed(MouseEvent e) {
81 Graphics2D g = (Graphics2D) ip.getGraphics();
82 g.setXORMode(Color.WHITE);
83 if(shouldErase) {
84 drawRect(g);
85 }
86 shouldErase = false;
87
88 mouseX = e.getX();
89 mouseY = e.getY();
90 }
91
92 public MouseHandler(ImagePanel ip, Stroke[] strokes) {
93 this.ip = ip;
94 this.strokes = strokes;
95 }
96
97 public void mouseDragged(MouseEvent e) {
98 Graphics2D g = (Graphics2D) ip.getGraphics();
99 g.setXORMode(Color.WHITE);
100
101 if(shouldErase) {
102 drawRect(g);
103 }
104
105 x = e.getX();
106 y = e.getY();
107
108 int w = ip.getWidth();
109 int h = ip.getHeight();
110
111 Insets insets = ip.getInsets();
112
113 if(x < insets.left) {
114 x = insets.left;
115 }
116 else if( x > w - insets.right) {
117 x = w - insets.right;
118 }
119
120 if(y < insets.top) {
121 y = insets.top;
122 }
123 else if(y > h - insets.bottom) {
124 y = h - insets.bottom;
125 }
126
127 index = index++ % 10;
128 drawRect(g);
129 g.dispose();
130
131 shouldErase = true;
132 }
133
134 private void drawRect(Graphics2D g) {
135 g.setStroke(strokes[index]);
136 g.drawRect(Math.min(mouseX, x), Math.min(mouseY, y), Math.abs(x - mouseX), Math.abs(y - mouseY));
137 }
138 }
139 }
140