import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class BalloonFall extends JPanel implements KeyListener, ActionListener { public static int WIDTH=800; public static int HEIGHT=600; private Font titleFont, regularFont; private ArrayList balloons; private Timer timer; /** * The class constructor will initialize the ArrayList<Balloon> * and other object fields (variables), including a Timer * object from the javax.swing.* library. The timer will * generate an Action Event, so that something happens * in regular intervals without the user typing anything. */ public BalloonFall() { //initialize variables here... titleFont = new Font("Roman", Font.BOLD, 18); regularFont = new Font("Helvetica", Font.PLAIN, 12); balloons = new ArrayList(); timer = new Timer(10, this); timer.start(); } /** * the main method makes an instance of our application and puts it in a JFrame * that will end the application when it is closed. * */ public static void main(String[] args) { BalloonFall app= new BalloonFall(); JFrame window = new JFrame("Balloon Fall"); window.setSize(WIDTH, HEIGHT); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(app); window.addKeyListener(app); window.setVisible(true); } /** * This is the method to change what is drawn to the screen: */ public void paintComponent(Graphics g){ //super.paintComponent(g); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(),getHeight()); g.setColor(Color.BLUE); g.setFont(titleFont); g.drawString("BalloonFall version 1.0", 20, 20); //g.drawString(balloons.size()+" Balloons", WIDTH-100, 20); g.setColor(Color.BLACK); g.setFont(regularFont); g.drawString("Press a Key to make a Balloon", 20, 40); for (Balloon x:balloons){ x.draw(g); } } /** * These 3 methods need to be declared to implement the KeyListener Interface * that listens for keys that are typed on the keyboard */ @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { int size = Balloon.randomInt(50, 80); int x = Balloon.randomInt(0, WIDTH); int y = Balloon.randomInt(-size, 0); balloons.add(new Balloon(x,y,size)); repaint(); } @Override /** * This method is needed to implement the ActionListener that listens for the timer * e.getKeyChar () and e.getKeyCode () will return the char (or its code) */ public void actionPerformed ( ActionEvent e) { // timer made an action event, so int i = 0; while ( i < balloons.size() ) { balloons.get(i).drop(); // if ( balloons.get(i).getBottom() > HEIGHT ) { balloons.remove (i); }else{ i++; } } repaint (); } }