Below is the code for the Mouse Test example discussed in section.
Driver class MouseTest.java
----------------------------
// Adapated from Core Java, chapter 8
public class MouseTest {
public static void main (String[] args) {
MouseFrame frame = new MouseFrame();
frame.start();
}
}
Panel class MousePanel.java
----------------------------
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
public class MousePanel extends JPanel {
private ArrayList squares;
private static final int SIDELENGTH = 10;
public MousePanel() {
squares = new ArrayList();
}
// Adds a square to the collection.
public void add(Point2D p) {
double x = p.getX();
double y = p.getY();
Rectangle2D r = new Rectangle2D.Double(x - SIDELENGTH / 2,
y - SIDELENGTH / 2, SIDELENGTH,
SIDELENGTH);
squares.add(r);
repaint();
}
// Finds the first square containing a point.
public Rectangle2D find(Point2D p) {
for (Rectangle2D r : squares) {
if (r.contains(p))
return r;
}
return null;
}
// Removes a square from the collection.
public void remove(Rectangle2D s) {
squares.remove(s);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// draw all squares
for (Rectangle2D r : squares)
g2.draw(r);
}
}
Frame class MouseFrame.java
----------------------------
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class MouseFrame {
private JFrame frame;
private MousePanel panel;
public MouseFrame() {
frame = new JFrame();
frame.setTitle("Mouse Test");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.WHITE);
panel = new MousePanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Rectangle2D current = panel.find(e.getPoint());
if (current == null)
panel.add(e.getPoint());
else if (e.getClickCount() == 2)
panel.remove(current);
}
});
}
public void start() {
frame.setVisible(true);
}
}