import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class HitTheBall extends Frame implements WindowListener, MouseListener {
private static int interval;
private static Timer timer;
private static int x;
private static int y;
public HitTheBall() {
super("Hit The Ball"); //Titolo finestra.
setSize(400, 400); //Dimensione finestra.
setResizable(false); //Finestra non ridimensionabile.
setVisible(true); //Finestra visibile.
setLocation(500, 200); //Posizione iniziale finestra.
addWindowListener(this); //Variabile d'ascolto della finestra.
addMouseListener(this); //Variabile d'ascolto del mouse.
}
public void paint(Graphics g) //Disegno il cerchio.
{
this.x = (int) (Math.random() * 350);
this.y = (int) (Math.random() * 350);
g.setColor(Color.red); //Imposto il colore del cerchio.
g.fillOval(x,y,50,50); //Imposto la dimensione del cerchio e la sua posizione.
}
//metodi listener eventi finestra
public void windowIconified(WindowEvent event){}
public void windowDeiconified(WindowEvent event){}
public void windowActivated(WindowEvent event){}
public void windowDeactivated(WindowEvent event){}
public void windowOpened(WindowEvent event){}
public void windowClosed(WindowEvent event){}
public void windowClosing(WindowEvent event){System.exit(0);}
public void mouseClicked(MouseEvent event){
eventOutput(event);
}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
public void mousePressed(MouseEvent event){
eventOutput(event);
}
public void mouseReleased(MouseEvent event){
eventOutput(event);
}
public MouseEvent eventOutput(MouseEvent event) {
System.out.println(event.getX() + " " + event.getY() );
if( Math.abs(event.getX()-x)<50 && Math.abs(event.getY()-y)<50)
interval = 5;
this.repaint();
return event;
}
public static void main(String[] args) {
HitTheBall gioco= new HitTheBall();
String secs="5";
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask()
{
public void run() {
System.out.println(setInterval());
if (interval == 0)
System.out.println("GIOCO TERMINATO");
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}