Snake Crawling Horiontally : Start And Stop Swing Based Java Program
Snake crawling is a program , in which snake position is set in a frame . The frame is provided with two buttons start and stop . When user presses a start button then the snake starts crawling in horizontal direction (or East direction) . User has the freedom to stop the movement of snake by pressing the stop button provided in the frame .This is an applet based application . Here snake is represented by **** .
A user can reset the position of the snake by changing the values in the program provided below .
The program given below is run by giving following inputs
Remember the above command is to run the program , before that you need to run one more command to get the class file of the program , that is
The points to understand and learn in this program are :
* It does not matter how many times you call repaint() method , it will only execute once in a method .
Remember the scope we are talking about is method .
* Whenever the repaint() is called , it initialises the applet and then run the paint() method again .
* drawString(s ,x ,y ) takes three parameters where s is the string that needs to show at (x,y) position in the
Please also note that in the awt and Swing , if we want to do some task or event at the press of button in our
frame then we use event handler. To use event handler , here , on pressing the button .
First step is to implement the ActionListener interface .Then we need to override the actionPerformed(event)
method . In the actionPerformed method , the action to perform after pressing the button ,code is written .
Here you can also make the snake move vertically ,what you need to do is that increment y with 10 each time in the for loop of the paint method .
In the last part of the code we are checking whether the snake does not cross the frame .
If it does then we are calling repaint() which actually initialises the paint method again , and our snake will continue to crawl in the frame horizontally.
There is another important thing in the code , to make the java compiler understand that its a Applet file we need to write the following code in the java program
/* <APPLET CODE=ClassName.class WIDTH=X HEIGHT=Y></APPLET> */
Without the above line the java compiler will treat the code as simple java program . But the above line helps java compiler to make the code appletviewer compatible.
Please find the Code below :
Snake Crawling Horiontally : Start And Stop Swing Based Java Program Reviewed by Sonia Rizvi on 03:29 Rating: