gpt4 book ai didi

java - 使用箭头键时我的图像消失

转载 作者:行者123 更新时间:2023-11-30 03:47:13 24 4
gpt4 key购买 nike

问题是,当我按下向下按钮时,图像(blueboy)消失了,而且它也没有向上移动,但可以左右移动,我不明白为什么?请帮忙。(我正在使用 RealJ)。如果有一个网站可以帮助我玩 2D 横向卷轴游戏,那对我也有帮助。

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class projectblue extends Applet implements ActionListener,KeyListener,MouseListener {

Image blueboy,trees; //image variable
int size = 4,jump = 50, cx = 1, cy = 1;

public void init() {

blueboy = getImage(getDocumentBase(),"png.png");
trees= getImage(getDocumentBase(),"background.jpg");
addKeyListener( this );
addMouseListener( this );
}

public void paint(Graphics g)
{
int width = trees.getWidth(this);
int height = trees.getHeight(this);
//System.out.println("" + cx +","+ cy);

//The later images are drawn on top of the earlier ones.
g.drawImage(trees, 1 ,1, width*size,height*7,this);
g.drawImage(blueboy, cx, cy, this);
}

public void actionPerformed(ActionEvent e) {
repaint();

}
public void left(){
cx = cx -100;
// blueboy moves left
}

public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
System.out.println("key pressed");
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
left();
}

if (key == KeyEvent.VK_RIGHT) {
cx = cx + 100;
//blueboy moves right
}

if (key == KeyEvent.VK_UP) {
while (cy >= 0 && cy <=1000)
cy = cy - 100;
if (cy < 0){
cy = 1;
//blueboy moves up, but if it goes out of bounds it goes back to the top
}
}

if (key == KeyEvent.VK_DOWN) {
while (cy >= 0 && cy <=1000)
cy = cy + 100;
if (cy > 1001){
cy = 999;
}
//blueboy moves down, but if it goes out of bounds it goes back to the bottim
}
repaint();
}

public void keyReleased(KeyEvent e) {
}

public void mouseEntered( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) { }
public void mouseReleased( MouseEvent e ) { }
public void mouseClicked( MouseEvent e ) {
int x = getX();
int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
} }

最佳答案

那些 while 循环会占用你的 GUI 线程,使你的动画变得毫无用处。它们不应该是 if block 吗?另外,您应该将所有 block 括在花括号中。你的缩进在骗你,大括号会告诉你原因。

此外,您还需要在绘制覆盖中调用 super.paint(g) 方法。

此外,这是一项作业吗?如果是,您是否需要使用 AWT/Applet 而不是 Swing 进行编码?

关于java - 使用箭头键时我的图像消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355439/

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