Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
62
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.awt.Color;
  2. import java.awt.Graphics;
  3. import java.awt.Graphics2D;
  4. import java.awt.Image;
  5. import java.awt.Toolkit;
  6.  
  7. import javax.swing.ImageIcon;
  8. import javax.swing.JPanel;
  9.  
  10.  
  11. public class Board4 extends JPanel implements Runnable {
  12.  
  13.     private Image star;
  14.     private Thread animate;
  15.     private int x, y;
  16.    
  17.     private final int Delay = 50;
  18.    
  19.    
  20.     public Board4() {
  21.         setBackground(Color.black);
  22.         setDoubleBuffered(true);
  23.        
  24.         ImageIcon image = new ImageIcon(this.getClass().getResource("star.png"));
  25.         star = image.getImage();
  26.         x = y = 10;
  27.     }
  28.    
  29.     public void addNotifty(){
  30.         super.addNotify();
  31.         animate = new Thread(this);
  32.         animate.start();
  33.     }
  34.    
  35.     public void paint(Graphics2D g){
  36.         super.paint(g);
  37.        
  38.         Graphics2D g2d = (Graphics2D)g;
  39.         g2d.drawImage(star, x, y, this);
  40.         Toolkit.getDefaultToolkit().sync();
  41.         g.dispose();
  42.     }
  43.    
  44.     public void cycle(){
  45.         x += 1;
  46.         y += 1;
  47.        
  48.         if(y > 240){
  49.             x = -45;
  50.             y = -45;
  51.         }
  52.     }
  53.    
  54.     public void run(){
  55.        
  56.         long beforeTime, timeDiff, sleep;
  57.        
  58.         beforeTime = System.currentTimeMillis();
  59.        
  60.         while(true){
  61.            
  62.             cycle();
  63.             repaint();
  64.            
  65.             timeDiff = System.currentTimeMillis() - beforeTime;
  66.             sleep = Delay - timeDiff;
  67.            
  68.             if (sleep < 0)
  69.                 sleep = 2;
  70.            
  71.             try
  72.             {
  73.                 Thread.sleep(sleep);
  74.             }
  75.             catch (InterruptedException e)
  76.             {
  77.                 System.out.println("interrupted");
  78.             }
  79.            
  80.             beforeTime = System.currentTimeMillis();
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement