CS 1410-20 Lab 11

In this lab, we will use the Swing GUI toolkit with drawing operations and for loops.

Drawing in A Frame

Create a new project and a new class called Snow. Use the following code, and run it:

  import javax.swing.*;
  import java.awt.*;
  
  class SnowPanel extends JPanel {
      static final int SIZE = 200;
  
      SnowPanel() {
          setPreferredSize(new Dimension(SIZE, SIZE));
      }
  
      protected void paintComponent(Graphics g) {
          g.setColor(new Color(0, 0, 255));
          g.fillRect(0, 0, SIZE, SIZE);
      }
  }
  
  public class Snow {
      public static void main(String[] args) {
          JFrame frame = new JFrame("Snow");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
          JPanel panel = new SnowPanel();
          frame.getContentPane().add(panel);
  
          frame.pack();
          frame.setVisible(true);
      }
  }

This program creates a frame that contains a 200 by 200 drawing area. The paintComponent method in SnowPanel is responsible for drawing the panel content, and it fills the area with blue.

Snow

Add an array of int to the SnowPanel class to represent snow depths.

In main create an array that is the same size as the panel (you can use SnowPanel.SIZE) and initialize the array by dropping 1000 random snow flakes:

  int snow[] = new int[SnowPanel.SIZE];
  for (int i = 0; i < 1000; i++) {
      int r = (int)(Math.random() * SnowPanel.SIZE);
      snow[r] = snow[r] + 1;
  }

Change paintComponent in SnowPanel to draw white snow at depth snow[i] at each horizontal position i.

Add Snow

After showing the frame, you can add more snow by changing snow and calling paint.repaint. Calling Thread.sleep slows down the snow.

  while (true) {
       int r = (int)(Math.random() * SnowPanel.SIZE);
       snow[r] = snow[r] + 1;
       panel.repaint(0, 0, 0, SnowPanel.SIZE, SnowPanel.SIZE);
       try { Thread.sleep(30); } catch (Exception e) { }
   }

Let It Snow

Instead of dropping new snow immediately to the ground, have a list of flakes that you gradually drop to the ground. Add a new flake to the list on each iteration at a random X position, move all flakes in the list on each iteration, and remove a flake from the list when it hits the ground.


Last update: Monday, December 6th, 2010
mflatt@cs.utah.edu