2017-06-03 18 views
0

私は初心者のプログラマーで、最近はJavaでゲームを作ろうとし始めました。ジャンプアニメーションが表示されないのはなぜですか?

これは基本的なもので、クラスは含まれていませんが、とにかくJPanelのジャンプアニメーションをスプライトとしてJLabelを使用して作成しようとしましたが、 Thread.sleep(millis)を使用してラベルをスキップし、ラベルを最後の位置に移動します。

JFrame frame = new JFrame("malario"); 
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); 

frame.setVisible(true); 
frame.setSize(700, 700); 
JPanel panel = new JPanel(); 

panel.setLayout(null); 
panel.setBackground(Color.blue); 
JLabel malario = new JLabel("Malario"); 
malario.setOpaque(true); 
malario.setBackground(Color.green); 
panel.add(malario); 

malario.setBounds(100, 550, 50, 50); 

JLabel platform = new JLabel(); 
platform.setOpaque(true); 
platform.setBounds(0,600,700,50); 
panel.add(platform); 
frame.setContentPane(panel); 
frame.addKeyListener(new KeyListener() { 
    int originalx = 100; 
    int originaly = 550; 
    int currentlocx = originalx; 
    int currentlocy = originaly; 

    @Override 
    public void keyTyped(KeyEvent e) { 
    } 

    @Override 
    public void keyReleased(KeyEvent e) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void keyPressed(KeyEvent e) { 

     if(e.getKeyCode()==KeyEvent.VK_RIGHT){ 
      malario.setBounds(currentlocx+10,currentlocy , 50, 50); 
      currentlocx = currentlocx+10; 
     } 

     if(e.getKeyCode()==KeyEvent.VK_LEFT){ 
      malario.setBounds(currentlocx-10,currentlocy , 50, 50); 
      currentlocx = currentlocx-10; 
     } 
     int jumpy=0; 
     if(e.getKeyCode()==KeyEvent.VK_UP){ 
      jumpy= currentlocy-100; 
      while(jumpy!=currentlocy){ 

       malario.setBounds(currentlocx,currentlocy-10 , 50, 50); 
       try { 
        Thread.sleep(1); 
       } catch (InterruptedException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
       currentlocy = currentlocy-10; 
      } 
     } 
    } 
}); 

} 
public static int Time(){ 
    return (int)System.currentTimeMillis(); 
} 
} 

答えて

2

Thread.sleep()は使用できません。

すべてのリスナーコードはイベント処理スレッド(EDT)で実行されます。これは、イベントの処理とGUIのペイントを担当するスレッドです。したがって、スレッドにスリープ状態を伝えると、ループ内のすべてのコードが実行を終了するまでGUIが再描画できないため、最後の位置にしかコンポーネントが表示されません。

代わりにSwing Timerを使用してアニメーションをスケジュールする必要があります。 Swing Tutorialを読んでください。上のセクションがあります

  1. Concurrency in Swingは - より多くの情報のためにタイマー

を使って上の例のために - EDT

  • How to Use Swing Timersについての詳細を説明しています。

    また、KeyListenerを使用しないでください。代わりにKey Bindingsを使用する方が良いです。このチュートリアルでは、How to Use Key Bindingsに関するセクションもあります。

    編集:

    参照:KeyboardAnimationMotion Using the Keyboardからの両方を示して作業例:アニメーションを実行する方法のキーバインド

  • を使用する方法

  • 関連する問題