JAVA学习日志 简单Frame。加载图片,小球的往复运动,线程

package MyGame;
/**
 * @auther 冯世磊
 * 窗口小项目
 */
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class GameFrame extends Frame{
	private int x=200,y=200;
	private boolean o=true;
	Image img=GameUtil.getImage("image/ball1.jpg");//加载小球
	public void launchFrame(){  //打开窗口的方法
		setSize(500,500); //设置窗口的长度和宽度
		setLocation(100,100);//设置窗口出现的位置
		setTitle("特训");
		setVisible(true);//设置窗口的可见性
		new PaintThread().start();//开启重画线程
		addWindowListener(
			new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
	
@Override
	public void paint(Graphics g) {
		g.drawImage(img, x, y, null);

		g.drawString("小球的往复运动", 100, 100);
		if(y==480){
			o=false;
		} 
		if(y==20){
			o=true;
		}
		if (o){
			y=y+2;
			}else{
			y-=5;	
			}
		System.out.println(y);
			
		    
	}
/**
 * 定义一个重画窗口的线程内部类
 * @author Administrator
 *
 */
	class PaintThread extends Thread{
		public void run(){
			while(true){
				repaint();//重画
				try {
					Thread.sleep(40);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}//设置每次重画延迟50毫秒
			}
		}
	}
public static void main(String[] args){
	GameFrame gf=new GameFrame();
	gf.launchFrame();
}

}
package MyGame;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class GameUtil {
	public static Image getImage(String path){
		URL u=GameUtil.class.getClassLoader().getResource(path);
		BufferedImage img=null;
		try {
			img=ImageIO.read(u);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return img;
	}
}


JAVA学习日志 简单Frame。加载图片,小球的往复运动,线程_第1张图片

你可能感兴趣的:(线程,thread,例子)