import java.awt.*; import java.awt.event.*; import java.awt.image.*; public class BallField extends Canvas { private BufferStrategy bufferStrategy; private int DOUBLE_BUFFER = 2; private int PAGE_FLIP = 3; private java.util.List balls; private java.util.Timer timer; private int width; private int height; public BallField(){ initFrame(); try{ createBufferStrategy(DOUBLE_BUFFER); // createBufferStrategy(PAGE_FLIP); bufferStrategy = getBufferStrategy(); }catch(IllegalStateException ex){ ex.printStackTrace(); System.exit(0); } balls = new java.util.ArrayList(); balls.add(new Ball(width, height)); timer = new java.util.Timer(); timer.schedule(new java.util.TimerTask(){ public void run(){ draw(); } }, 1000, 60); } public void addBall(){ balls.add(new Ball(width, height)); } public void changeBallDirection(){ for(int i = 0 ; i < balls.size() ; i++){ ((Ball)balls.get(i)).turn(); } } private void initFrame(){ Frame frame = new Frame("Ball Field"); frame.setIgnoreRepaint(true); frame.setBounds(100, 100, 600, 600); frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent event){ System.exit(0); } }); frame.add(this, BorderLayout.CENTER); Button increaseButton = new Button("Ball Increase"); increaseButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ addBall(); } }); Button directionButton = new Button("Ball Direction Change"); directionButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ changeBallDirection(); } }); Button finishButton = new Button("Finish"); finishButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ System.exit(0); } }); Panel panel = new Panel(); panel.setBackground(Color.lightGray); panel.add(increaseButton); panel.add(directionButton); panel.add(finishButton); frame.add(panel, BorderLayout.SOUTH); frame.setVisible(true); Dimension dim = getSize(); width = dim.width; height = dim.height; } private void clear(Graphics2D g){ g.setPaint(Color.white); g.fillRect(0, 0, width, height); } public void draw(){ for(int i = 0 ; i < balls.size() ; i++){ ((Ball)balls.get(i)).move(); } Graphics2D g = (Graphics2D)bufferStrategy.getDrawGraphics(); if(!bufferStrategy.contentsLost()){ clear(g); for(int i = 0 ; i < balls.size() ; i++){ ((Ball)balls.get(i)).drawShadow(g); } for(int i = 0 ; i < balls.size() ; i++){ ((Ball)balls.get(i)).draw(g); } bufferStrategy.show(); g.dispose(); } } public static void main(String[] args){ BallField field = new BallField(); } }