Witam,
chciałbym by w moim programe, były zliczane kliknięcia myszy.
- Wszystkie kliknięcia
- Tylko te którymi trafiliśmy w kwadrat
A na końcu zostały wyświetlone ile trafiliśmy i ile było wszystkich. Ma ktoś może jakiś pomysł jak to zrobić ??
A oto kod:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.util.Timer;
import javax.swing.*;
public class Mouse extends JComponent {
Date start = new Date();
Timer timer;
public Mouse()
{
squares = new ArrayList<Rectangle2D>(1);
current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());
time();
}
public void time()
{
timer = new Timer();
timer.schedule(new Time(),start, sec);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(drawRectangle)
{
int x = new Random().nextInt(700);
int y = new Random().nextInt(600);
Rectangle2D rec = new Rectangle2D.Double(x,y,20,20);
add(new Point(x,y));
drawRectangle = false;
g2.setPaint(Color.BLACK);
g2.fill(rec);
if(i == 30)
{
Font font = new Font("SansSerif", Font.BOLD + Font.ITALIC, 155);
g2.setFont(font);
String message = "Koniec";
g2.drawString(message, 150, 250);
}
}
}
public void add(Point2D p)
{
double x = p.getX();
double y = p.getY();
current = new Rectangle2D.Double(x, y, 20, 20);
squares.add(current);
}
public void remove(Rectangle2D s)
{
if(s == null)
return;
if(s == current)
{
current = null;
squares.remove(s);
repaint();
}
}
public Rectangle2D find(Point2D p)
{
for(Rectangle2D r : squares)
{
if(r.contains(p))
return r;
}
return null;
}
private class Time extends TimerTask
{
public void run() {
drawRectangle = true;
repaint();
i++;
if( i == 30)
{
timer.cancel();
}
}
}
private class MouseHandler extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent event) {
super.mouseClicked(event);
current = find(event.getPoint());
if(current != null)
remove(current);
}
}
private class MouseMotionHandler implements MouseMotionListener
{
@Override
public void mouseDragged(MouseEvent event) {
//brak opcji
}
@Override
public void mouseMoved(MouseEvent event) {
if(find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
private int i = 0;
private int sec = 1250;
private boolean drawRectangle = false;
private Rectangle2D current;
private ArrayList<Rectangle2D> squares;
}