今天的问题让我大吃一惊。我正在创建一个程序,允许用户跳转并向左或向右移动,问题在于每当我尝试跳过程序冻结时......我的代码背后的想法很简单,每当用户按下空格(跳转)时矩形“跳跃”向上,如果矩形的y在障碍物上方的某个高度内(在这种情况下是一个矩形,具有砖块,砖,砖和砖块是障碍物)那么动画应该停止并且矩形应该在障碍物顶部就位时等待下一个命令。为此,在while循环和检查的每次迭代期间调用一个方法stayOnBrick;在跳转期间,如果y在所需范围内,并且如果y为它,则设置boolean jump = true,这应该在下一次迭代中打破循环以及将y设置为所需的值。但是当空间被按下时,没有任何反应,或者我应该说程序冻结了。想法?
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyTest extends Core implements KeyListener{
Window w;
public int x,y;
boolean jump = true;
public int brickx, bricky, brickw, brickh;
public static void main(String args[]){
new KeyTest().run();
}
private String mess = "";
//init also called init from superclass
public void init(){
super.init();
Window w = s.getFullScreenWindow();
w.setFocusTraversalKeysEnabled(false);
w.addKeyListener(this);
y = s.getHeight()-15;
mess = "Press esc to exit";
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
e.consume();
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ESCAPE){
stop();
}else if(keyCode == KeyEvent.VK_SPACE){
mess = "Pressed: " + KeyEvent.getKeyText(keyCode);
while(y>s.getHeight()-200){
stayOnBrick();
if(jump==false){break;}
else{ try{
y-=20;
w.repaint();
Thread.sleep(40);
}catch(Exception jumpError){
System.out.println("Error in Jumping");
}
}
while(y<s.getHeight()-15){
stayOnBrick();
if(jump==false){
w.repaint();
break;}
else{
try{
y+=20;
Thread.sleep(40);
w.repaint();
}catch(Exception jumpError){
System.out.println("Error in Jumping");
}
}
}
}
}
else if(keyCode == e.VK_RIGHT){
if(x>=s.getWidth()-30){x=s.getWidth()-30;}
x+=20;
w.repaint();
}
else if(keyCode == e.VK_LEFT){
if(x<=0){x=0;}
x-=20;
w.repaint();
}
e.consume();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int keyCode = e.getKeyCode();
mess = "Released: " + KeyEvent.getKeyText(keyCode);
jump = true;
e.consume();
}
@Override
public synchronized void draw(Graphics2D g){
brickx=0; bricky=s.getHeight()-100; brickw=300; brickh=20;
Window w = s.getFullScreenWindow();
g.setColor(w.getBackground());
g.fillRect(0, 0, s.getWidth(), s.getHeight());
g.setColor(w.getForeground());
g.fillRect(x, y, 30, 15);
g.drawString(mess, 30, 30);
g.setColor(Color.BLUE);
g.fillRect(brickx, bricky, brickw, brickh);
}
public void stayOnBrick(){
if(y<bricky && y>bricky-30){
y=bricky-15;
jump = false;
}
else{jump = true;}
}
}
答案 0 :(得分:2)
每当我尝试跳过程序冻结
我首先看一下问题的原因Concurrency in Swing。
我建议您查看How to use Swing Timers可能的解决方案。
我还建议您查看How to Use Key Bindings以解决与KeyListener
您可能会发现How to make sprite jump in java?和JApplet creates a ball that bounces and gets progressively less high in Java有用