Practice Programs For Applets
Practice Programs For Applets
2) Write a Java program to display current time of a day using java applets and use Date class.
import java.applet.*; import java.awt.*; import java.util.Date; import java.text.DateFormat; /** An Applet to display the current time */ public class ClockApplet extends Applet implements Runnable { /** A Thread to run the timer */ protected Thread timerThread; /** The date object */ Date date = new Date(); /** The date format */ protected DateFormat format = DateFormat.getTimeInstance(); /* Applet Lifestyle Methods */ public void start() { timerThread = new Thread(this, "Clock"); timerThread.start(); } public void stop() { if (timerThread == null) return;
timerThread = null; } /** Show the time, and wait a while. */ public void run() { while (timerThread != null) { repaint(); // request a redraw try { timerThread.sleep(1000); } catch (InterruptedException e){ /* do nothing*/ } } } /** Display the time. */ public void paint(Graphics g) { date.setTime(System.currentTimeMillis()); g.drawString(format.format(date), 2, 10); } }
3) Write an applet that draws a checkerboard. Assume that the size of the applet is 160 by 160 pixels. Each square in the checkerboard is 20 by 20 pixels. The checkerboard contains 8 rows of squares and 8 columns. The squares are red and black. Here is a tricky way to determine whether a given square is red or black: If the row number and the column number are either both even or both odd, then the square is red. Otherwise, it is black. Note that a square is just a rectangle in which the height is equal to the width, so you can use the subroutine g.fillRect() to draw the squares. Here is an image of the checkerboard:
import java.awt.*; import java.applet.*; public class Checkerboard extends Applet { /* This applet draws a red-and-black checkerboard. It is assumed that the size of the applet is 160 by 160 pixels. */ public void paint(Graphics g) { int row; // Row number, from 0 to 7 int col; // Column number, from 0 to 7 int x,y; // Top-left corner of square for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++) { x = col * 20; y = row * 20; if ( (row % 2) == (col % 2) )
g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(x, y, 20, 20); } } // end for row } // end paint()