FileDocCategorySizeDatePackage
simpleEvent.javaAPI DocExample2148Thu Nov 23 15:25:12 GMT 2000None

simpleEvent.java

/*simpleEvent.java
by D Mullier Nov 2000

Sets up a text field and a button. Displays "Ouch" randomly on the screen
a number of times as indicated by the text field.

REFER to your week 9 notes
*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;	//step 1
import java.math.*;


public class simpleEvent extends Applet implements ActionListener //step 2
{
	private TextField myText;	//step 3
	private Button but1;
	private int number=0;
	private boolean hit=false;
	
	public void init() //step 4
	{
		//step 5
		myText = new TextField(10);			//create a new textfield object
		add(myText);											//add the new object to the window display
		myText.addActionListener(this);	//add the event handling mechanism
		Button but1 = new Button("HitMe!"); //make a new button with "HitMe!" displayed in it
		add(but1);											//add it to the window
		but1.addActionListener(this);		//add the event handling mechanism

	}

	public void actionPerformed(ActionEvent ae) //step 6
	{
		String tempString;
		
		if (ae.getSource()==myText)			//was it the text event?
		{
			tempString = myText.getText(); //get the string out of the text field
			number = Integer.parseInt(tempString);	//convert it to an integer
		}
		else
		{
			hit=true;											//turn our switch on to say the button was pressed
		}
		repaint();											//call paint to update the display
	}//end init
	
	public void paint(Graphics g)
	{
		int x,y;
		if (hit == true)							//is the switch on (i.e. was the button pressed)?
		{
			hit=false; //reset flag (work out why, by seeing what would happen if this line were not here)
			for(int i=0; i<number;i++)	//print Ouch out the number of times myText in the text box
			{
				x = (int) (Math.random() * 100)+1;	//calculate a random x position
				y = (int) (Math.random() * 100)+1;	//calculate a random y position
				g.drawString("Ouch!!!",20+x+i,20+y+i);	//print at the random position
			}
		}
		if (number != 0)	//if a number was typed in display it.
		{
			g.drawString("You typed in " + number,100,125);
		}
		
	}//end paint
}//end applet