import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class BallsJFrame extends JFrame implements ChangeListener{
private JSpinner spinner;
private BallsCanvas canvas;
public BallsJFrame(){
super("µ¯µ¯Çò");
setBounds(500, 300, 400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Color colors[]={Color.red,Color.black,Color.blue,Color.cyan,Color.yellow};
canvas=new BallsCanvas(colors,100);
getContentPane().add(canvas);

JPanel panel=new JPanel();
getContentPane().add(panel,BorderLayout.SOUTH);
panel.add(new JLabel("Delay"));
spinner= new JSpinner();
spinner.setValue(100);
panel.add(spinner);
spinner.addChangeListener(this);

setVisible(true);
}
public static void main(String[] args) {
new BallsJFrame();
}

 

@Override
public void stateChanged(ChangeEvent e) {
int d=100;
try {
d = Integer.parseInt("" + spinner.getValue());
} catch (Exception e2) {
JOptionPane.showMessageDialog(this, "·Ç·¨×Ö·ûÊäÈ룡");
}
canvas.setDelay(d);
}

}
class BallsCanvas extends Canvas implements ActionListener,FocusListener{
private Ball balls[];
private Timer timer;
private int delay=100;

public BallsCanvas(Color colors[],int d){
this.delay=d;
this.balls=new Ball[colors.length];

for(int i=0,x=40;i balls[i]=new Ball(x,x,colors[i]);
}

this.addFocusListener(this);
timer=new Timer(delay,this);
timer.start();

}

public void setDelay(int delay){
this.delay=delay;
timer.setDelay(delay);//*********

}
public void paint(Graphics g){
for(int i=0;i g.setColor(balls[i].color);
balls[i].x=balls[i].left?balls[i].x-5:balls[i].x+5;
if(balls[i].x<=0||balls[i].x+20>=this.getWidth()){
balls[i].left=!balls[i].left;

}
balls[i].y=balls[i].up?balls[i].y-5:balls[i].y+5;
if(balls[i].y<=0||balls[i].y+20>=this.getHeight()){
balls[i].up=!balls[i].up;

}

g.fillOval(balls[i].x , balls[i].y,20,20);
}

}

class Ball{
private int x,y;
private Color color;
boolean left,up;

public Ball(int x,int y,Color color){
this.x=x;
this.y=y;
this.color=color;

}


}

@Override
public void actionPerformed(ActionEvent e) {
repaint();

}

@Override
public void focusGained(FocusEvent e) {
timer.stop();
}

@Override
public void focusLost(FocusEvent e) {
timer.restart();

}
}