gpt4 book ai didi

java - 我的 keyListener 发生了什么?

转载 作者:行者123 更新时间:2023-12-02 02:25:30 26 4
gpt4 key购买 nike

在下面的代码中,我试图创建一个 Frog 游戏,其中一个“白点”代表 Frog 。然而,一切都很顺利,直到我添加了 keyListener,这是我刚刚从观看几个 YouTube 视频中学到的。问题是公共(public)课中的“FINAL”是红色下划线的。我所做的一切都是按照我观看的视频进行的;我有“keyPress”...我确实相信在 public void init 中使用“this”有问题。请有人帮忙。

import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.Graphics;

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class FINAL extends Applet implements Runnable,KeyListener{
Thread t;
Image BGImage;
Image i;
Graphics DG;
int x =0;
int y = 100;
int a;
int b;
int c;
int d;
int e;
int f;

int h = 20;
int j = 480;

public void init()
{
this.addKeyListener(this);
setSize(500,500);
BGImage = getImage(getCodeBase(),"frogger_background.jpg");

}

public void start()
{
if(t==null)
{
t=new Thread(this,"New Thread");
t.start();
}
}

public void stop()
{
if(t!=null)
{
t=null;
}
}

public void run()
{
Thread t1=Thread.currentThread();
while(t==t1)
{
repaint();
try
{
Thread.sleep(100); //slepp 100 ms
}
catch(Exception e)
{ }
}
}

@Override
public void keyPressed(KeyEvent e){
//int keyCode = e.getKeyCode();
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
j = j + 1;
break;

case KeyEvent.VK_UP:
j = j - 1;
break;

case KeyEvent.VK_LEFT:
h = h - 1;
break;

case KeyEvent.VK_RIGHT:
h = h + 1;
break;
}
}

@Override
public void keyReleased(KeyEvent e){

}

@Override
public void update(Graphics g){
i = createImage(this.getSize().width,this.getSize().height);
DG = i.getGraphics();
paint(DG);
g.drawImage(i,0,0,500,500,this);
}



@Override
public void paint(Graphics g){
//Graphics2D g2 = (Graphics2D)g;
x = x+1;
a = x%500+30;
b = 5*(x%500);
c = 3*(x%500);
d = 4*(x%500)+50;
e = 6*(x%500)+10;
f = 7*(x%500)+20;
g.drawImage(BGImage, 0, 0, this);

g.setColor(new Color(160,82,45));
g.fillRoundRect(a, y, 120, 35, 5, 5);

g.setColor(new Color(160,82,45)); //Wood#2
g.fillRoundRect(b, y+50, 120, 35, 5, 5);


g.setColor(new Color(160,82,45)); //Wood#3
g.fillRoundRect(c, y+100, 120, 35, 5, 5);


g.setColor(Color.RED);
g.fillRoundRect(d, 300, 60, 25, 5, 5);


g.setColor(Color.BLUE);
g.fillRoundRect(e, 350, 60, 25, 5, 5);


g.setColor(Color.YELLOW);
g.fillRoundRect(f, 400, 60, 25, 5, 5);

g.setColor(Color.WHITE);
g.fillOval(j,h,20,20);
if (j<0){

}
System.out.println("j =" + j);
System.out.println("h =" + h);

}

}

最佳答案

FINAL 不满足 KeyListener interface 的契约(Contract)要求,特别是 keyTyped

您需要添加...

@Override
public void keyTyped(KeyEvent e) {
}

到你的类(class)

Applet 也已被弃用,您应该避免使用它。

我建议在 Swing 中投入时间或JavaFX相反

关于java - 我的 keyListener 发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com