Computer questions (Elementary)-Snowball example code (Java)
In the previous section, the effects of the stars are achieved. This section will implement a small example of snowball rolling. here we need to use the re-painting and thread knowledge. The Code is as follows:
import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Panel;public class SnowBall {public static void main(String[] args) {Frame frame=new Frame();frame.setBackground(Color.BLACK);frame.setSize(1024, 768);MyPanel myPanel=new MyPanel();frame.add(myPanel);Thread thread=new Thread(myPanel);thread.start();frame.show();}}class MyPanel extends Panel implements Runnable{int x=120;int y=10;@Overridepublic void paint(Graphics g) {g.setColor(Color.WHITE);g.fillOval(x, y, 20, 20);}@Overridepublic void run() {while (true) {y++;if(y>768){y=0;}repaint();}}}
At this time, the running finds that the ball does not move, but it is not a problem of code, because the CPU runs too fast, here we can let the thread sleep for a while and then execute the next time, add in while:
try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}
When you run the instance again, you can see that the ball keeps falling.