Guest User

Untitled

a guest
May 20th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. import java.applet.*;
  2. import java.awt.*;
  3.  
  4. public class MovingBall extends Applet implements Runnable
  5. {
  6.     int x_pos = 10;
  7.     int y_pos = 100;
  8.     int x_speed = 1;
  9.     int radius = 20;
  10.     private Image dbImage;
  11.     private Graphics dbg;
  12.     int appletsize_x = 300;
  13.     int appletsize_y = 300;
  14.    
  15. public void init() {
  16.     setBackground (Color.blue);
  17. }
  18.  
  19. public void start() {
  20.     Thread th = new Thread(this);
  21.     th.start();
  22. }
  23.  
  24. public void stop() { }
  25.  
  26. public void destroy() { }
  27.  
  28. public void run () {
  29.     Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  30.  
  31.     while (true)
  32.     {
  33.         x_pos += x_speed;
  34.         if (x_pos > appletsize_x - (radius * 6))
  35.         {
  36.         x_speed = -1;
  37.         }
  38.         else if (x_pos < radius)
  39.         {
  40.        
  41.         x_speed = +1;
  42.         }
  43.        
  44.    
  45.     repaint();
  46.  
  47.     try
  48.     {
  49.    
  50.     Thread.sleep (20);
  51.     }
  52.     catch (InterruptedException ex)
  53.     {
  54.    
  55.     }
  56.  
  57.    
  58.     Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
  59.     }
  60. }
  61.  
  62. public void paint (Graphics g) {
  63.      
  64.     g.setColor (Color.red);
  65.  
  66.    
  67.     g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
  68. }
  69. public void update(Graphics g){
  70.    
  71.     if (dbImage == null)
  72.     {
  73.     dbImage = createImage (this.getSize().width, this.getSize().height);
  74.     dbg = dbImage.getGraphics ();
  75.     }
  76.  
  77.    
  78.     dbg.setColor (getBackground ());
  79.     dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
  80.  
  81.    
  82.     dbg.setColor (getForeground());
  83.     paint (dbg);
  84.  
  85.    
  86.     g.drawImage (dbImage, 0, 0, this);
  87. }
  88.  
  89. }
Add Comment
Please, Sign In to add comment