java图片移动(键盘控制)

原文地址  http://www.xuebuyuan.com/1591626.html



import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Sample extends Frame {

	private Image img = null;
	private Image img2 = null;
	private Image img3 = null;
	int by = 30;

	public static void main(String[] args) {
		new Sample();
	}

	public Sample() {
		this.setSize(803, 603);
		this.setLocation(100,100);
		
		img = Toolkit.getDefaultToolkit().createImage("img/11.jpg");
		img3 = Toolkit.getDefaultToolkit().createImage("img/11.jpg");
		img2 = Toolkit.getDefaultToolkit().createImage("img/11.jpg");
		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		
		this.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_RIGHT)
				by = by + 5;
				else if(e.getKeyCode() == KeyEvent.VK_LEFT)
				by = by -5;
				repaint();
			}
		});
		this.setVisible(true);
	}

	public void paint(Graphics g) {
		g.drawImage(img2, 100, 100,100,100, this);
		g.drawImage(img3, by, 490,100,100, this);
		g.drawImage(img, 580, 260,100,100,this);
	}
}

你可能感兴趣的:(java,图片,JAVA)