Sun Microsystems

Wake Tech

Your Guide to Java

Samples
Syllabus
Assignments
Instructors
Introduction
Samples Index
 

CSC 148 Java Programming
Sample Solutions
Chapter Nine

// Exercise 9.7 Solution

// Concentric.java

// This program draws concentric circles

import java.applet.Applet;

import java.awt.*;

public class Concentric extends Applet {

public void paint( Graphics g )

{

for ( int x = 0; x <= 160; x += 10 ) {

int y = 160 - ( x * 2 );

g.drawRoundRect( x + 10, x + 10, y, y, y, y );

}

}

}

 

 

// Exercise 9.8 Solution

// Circles.java

// This program draws concentric circles

import java.applet.Applet;

import java.awt.*;

public class Circles extends Applet {

public void paint( Graphics g )

{

for ( int x = 0; x <= 160; x += 10 ) {

int y = 160 - ( x * 2 );

g.drawArc( x + 10, x + 10, y, y, 0, 360 );

}

}

}

 

 

// Exercise 9.24 Solution

// Saver1.java

// Program simulates a simple screen saver

import java.applet.Applet;

import java.awt.*;

public class Saver1 extends Applet {

public void paint( Graphics g )

{

int x, y, x1, y1, count = 0;

while ( true ) {

g.setColor( Color.green );

// assume html size is 200 x 200

x = ( int ) ( Math.random() * 200 );

y = ( int ) ( Math.random() * 200 );

x1 = ( int ) ( Math.random() * 200 );

y1 = ( int ) ( Math.random() * 200 );

g.drawLine( x, y, x1, y1 );

++count;

// slow the drawing down

for ( int q = 1; q < 1000000; q++ )

; // do nothing

if ( count == 100 ) {

g.setColor( Color.white );

g.fillRect( 0, 0, 200, 200 );

count = 0;

}

}

}

}

 

 

// Exercise 9.25 Solution

// Saver2.java

// Program simulates a simple screen saver

// Note: When entering a value in the text

// field, it may take some time before the

// event is handled.

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class Saver2 extends Applet

implements ActionListener {

private TextField input;

private Label prompt;

private int count;

public void init()

{

input = new TextField( 5 );

input.addActionListener( this );

prompt = new Label( "Enter number of lines:" );

add( prompt );

add( input );

}

public void paint( Graphics g )

{

int x, y, x1, y1, temp = count;

while ( temp > 0 ) {

g.setColor( Color.green );

// assume html size is 200 x 200

x = ( int ) ( Math.random() * 200 );

y = ( int ) ( Math.random() * 200 );

x1 = ( int ) ( Math.random() * 200 );

y1 = ( int ) ( Math.random() * 200 );

g.drawLine( x, y, x1, y1 );

--temp;

// slow the drawing down

for ( int q = 1; q < 1000000; q++ )

; // do nothing

}

g.setColor( Color.white );

g.fillRect( 0, 0, 200, 200 );

temp = count;

repaint();

}

public void actionPerformed( ActionEvent e )

{

count = Integer.parseInt( input.getText() );

input.setText( "" );

repaint();

}

}