修复背景图片小程序

时间:2017-04-12 07:49:54

标签: java applet awt

我的代码存在一些问题。 我想修复背景图像以保持固定,同时其他组件可以移动。 这是一个简单的游戏,其中一个圆圈避开正方形,但游戏的结构将被进一步添加。

这是我的代码

import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;

import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{

    Thread r;
    Image bg = null;
    int a,b;
    int x = 600;
    int y = 400;
    public void init(){
        setSize(600,600);
        try 
        { 
            MediaTracker tr = new MediaTracker (this);
            bg = getImage
            (new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
            tr.addImage(bg, 0);
        } catch (Exception e) { System.out.println(e.toString());

        }
    }
    public void start(){
        if(r == null){
            r = new Thread(this);
            r.start();
        }
    }
    public void paint(Graphics g){
        g.drawImage(bg,0,0,this); 
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(20));
        g2.draw(new Line2D.Float(0, 500, 600, 500));
        g.fillRect(x, y, 20, 20);
    }
    public void pp(Graphics g){

    }
    public void run() {
        Thread Th = Thread.currentThread();
        while(r == Th) {
            if(a < 600) {
                a = a+10;
                x = x-10;
                repaint();
            }else{
                repaint();
                a = 30;
                x = 600;
            }
            try {
                Thread.sleep(100);
                } catch(InterruptedException e) { }
            }
    }
    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

}

如果你运行代码,你会看到线和背景将被加载很多时间......

0 个答案:

没有答案