Computer questions (Elementary)-Snowball example code (Java)

Source: Internet
Author: User

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.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.