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

标签 java animation applet keyboard awt

问题是,当我按下向下按钮时,图像(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/

相关文章:

java - 对因 Profile 而尚未创建的 bean 进行 Null 检查

css - React 过渡动画未按预期工作

java - 暂时减慢处理速度

java - 当组件添加到 JAVA 的单独线程中时,如何立即重绘容器?

java - Topaz Signature Applet 未连接到 COM1 上的 Serial ClipGem

java - 在 Java 中对文本文件进行排序

java - gradlew setupDecompWorkspace 错误 : Could not reserve enough space

java - 将复选框值存储到 Firebase 数据库

Java applet 替代技术

java - 是否可以使用 JavaFx 创建 Java 小程序?