// Stage.java-- illustrates the stage lighting example of the book import java.applet.*; import java.awt.*; import java.lang.*; import java.util.*; public class Stage extends Applet { TextField x_text, y_text, r_text; Label x_label, y_label, r_label; Button draw_button; Graphics my_graphics; // These determine the origin in Graphics coordinates int origin_x = 125; int origin_y = 60; // setup the gui public void init () { x_text = new TextField("0", 3); y_text = new TextField("0", 3); r_text = new TextField("0", 3); x_label = new Label("x:"); y_label = new Label("y:"); r_label = new Label("r:"); add(x_label); add(x_text); add(y_label); add(y_text); add(r_label); add(r_text); draw_button = new Button("Plot"); add(draw_button); my_graphics = this.getGraphics(); } // Draws a light on the stage_canvas with radius r // at x,y. void draw_light ( double x, double y, double r ) { // the Graphics.drawOval method draws an ellipse inside a rectangle, // but we are given a radius and center. The coords of the upper left // corner of the square bounding our circle is (x-r,y-r); int xcoord = (int)((x + origin_x) - r); int ycoord = (int)((origin_y - y) - r); int d = (int)(2 * r); // Draw the circles in red Color old_color = my_graphics.getColor(); my_graphics.setColor(Color.red); my_graphics.drawOval (xcoord, ycoord, d, d); my_graphics.setColor(old_color); } public boolean handleEvent ( Event e ) { if ( (e.target == draw_button) && e.id == Event.ACTION_EVENT ) { // try to convert the contents of the text fields // to numbers; if we succeed, draw the appropriate // stage light boolean number_ok = true; double x,y,r; try { x = Double.valueOf(x_text.getText()).doubleValue(); } catch (java.lang.NumberFormatException ex ) { number_ok = false; x = y = r = 0.0; } try { y = Double.valueOf(y_text.getText()).doubleValue(); } catch (java.lang.NumberFormatException ex) { number_ok = false; x = y = r = 0.0; } try { r = Double.valueOf(r_text.getText()).doubleValue(); } catch (java.lang.NumberFormatException ex) { number_ok = false; x = y = r = 0.0; } if ( number_ok ) draw_light ( x,y,r ); } return false; } // Draw cyan lines through the origin public void paint (Graphics g) { Color old_color = g.getColor(); Dimension d = size(); g.setColor(Color.cyan); g.drawLine(origin_x,0, origin_x, d.height); g.drawLine(0,origin_y, d.width, origin_y); g.setColor(old_color); } } // class Stage