Bardzo prosta (i migająca) implementacja (na bazie powyższej):
import java.awt.event.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class projekt extends JApplet implements MouseListener,
MouseMotionListener {
public class MyRect {
private int y;
private int x;
private Color color;
public int getY() {
return y;
}
public int getX() {
return x;
}
public Color getColor() {
return color;
}
public MyRect(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
}
String tekst = " ";
int x;
int y;
private ArrayList<MyRect> rects = new ArrayList<MyRect>();
Random r = new Random();
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void start() {
}
public void stop() {
}
public void mouseDragged(MouseEvent evt) {
x = evt.getX();
y = evt.getY();
tekst = "Przycisk wciśnięty, ";
tekst += "współrzędne: x = " + evt.getX() + ", ";
tekst += "y = " + evt.getY();
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
rects.add(new MyRect(x, y, c));
repaint();
}
public void paint(Graphics gDC) {
gDC.clearRect(0, 0, getSize().width, getSize().height);
gDC.drawString(tekst, 20, 20);
for (MyRect r : rects) {
gDC.setColor(r.getColor());
gDC.fillRect(r.getX(), r.getY(), 10, 10);
}
}
public void mouseClicked(MouseEvent evt) {
int button = evt.getButton();
switch (button) {
case MouseEvent.BUTTON1:
tekst = "Przycisk 1, ";
break;
case MouseEvent.BUTTON3:
tekst = "Przycisk 2, ";
break;
case MouseEvent.BUTTON2:
tekst = "Przycisk 3, ";
break;
default:
tekst = " ";
}
tekst += "współrzędne: x = " + evt.getX() + ", ";
tekst += "y = " + evt.getY();
}
public void mouseEntered(MouseEvent evt) {
}
public void mouseExited(MouseEvent evt) {
}
public void mousePressed(MouseEvent evt) {
}
public void mouseReleased(MouseEvent evt) {
}
public void mouseMoved(MouseEvent evt) {
}
public void destroy() {
}
public String getAppletInfo() {
return "Title: \nAuthor: \nA simple applet example description. ";
}
public String[][] getParameterInfo() {
String paramInfo[][] = {
{ "firstParameter", "1-10", "description of first parameter" },
{ "status", "boolean", "description of second parameter" },
{ "images", "url", "description of third parameter" } };
return paramInfo;
}
}