如何使用appletviewer使用箭头键在java中移动对象

时间:2018-04-03 15:41:46

标签: java

我正在学习java,我正在尝试使用创建一个小型游戏应用程序 java awt ...这里是我的代码..虽然不完整..我无法使用左侧或左侧向左或向右移动火箭 使用keylistener右键导航键... 你能不能帮我弄清楚错误是什么

import java.applet.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/* <applet code="demo" height =1000 width =1000></applet>*/

public class demo extends Applet implements Runnable,KeyListener
{

    int b=10;
    int keypressX=0;

    int min=60,max=940,min1=10,max1=300;
    double[] x= new double[10];
    double[] y=new double[10];
    Thread t=null;
    public void init()
    {

        setBackground(Color.black);
        t= new Thread(this,"First");
        t.start();


    }
    public void run()
    {

        for( ; ; )
        {

            for(int k=0;k<10;k++){

            x[k] = Math.random()*((max-min)+1)+min;
            y[k] = Math.random()*((max1-min1)+1)+min1;


            }

            while(b<=500)
            {
                try{
                Thread.sleep(250);

                b+=10;

                repaint();}
                catch(Exception e){}
            }
            b=10;
        }


    }

    public void keyPressed(KeyEvent ke){
        int key=ke.getKeyCode();
        if(key== KeyEvent.VK_LEFT){
            keypressX=-10;

        }
        if(key == KeyEvent.VK_RIGHT){
            keypressX=10;

        }
        repaint();

    }
    public void keyReleased(KeyEvent ke){}
    public void keyTyped(KeyEvent ke){}

    public void paint(Graphics g){


        for(int i=0;i<10;i++)
        {
            g.setColor(Color.white);
            g.fillOval((int)x[i],(int)y[i]+b,30,30);
        }



        g.setColor(Color.gray);
        g.fillRect(480+keypressX,800,40,100);
        g.setColor(Color.blue);
        g.fillRect(460+keypressX,825,20,50);
        g.fillRect(520+keypressX,825,20,50);
        g.setColor(Color.yellow);
        g.fillRect(490+keypressX,830,20,50);
        int xpts[]={480+keypressX,500+keypressX,520+keypressX};
        int ypts[]={800,750,800};
        g.setColor(Color.blue);
        g.fillPolygon(xpts,ypts,3);



        int xpt[]={480+keypressX,520+keypressX,510+keypressX,490+keypressX};
        int ypt[]={950,950,900,900};
        g.setColor(Color.blue);
        g.fillPolygon(xpt,ypt,4);
    }
}

0 个答案:

没有答案