2012-01-18 15 views
3
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Racing extends JFrame { 
private static final long serialVersionUID = -198172151996959655L; 

//makes the screen size 
final int WIDTH = 900, HEIGHT = 650; 

//keeps track of player speed 
double plSpeed = .5; 

//numbers that represent direction 
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, STOP = 5, START = 6; 

//keeps track of player direction 
int p1Direction = START; 

//makes player 1's car 
Rectangle p1 = new Rectangle (100, 325, 30, 30); 
Rectangle foreground = new Rectangle(500, 500, 200, 200); 

//constructor 
public Racing() { 
    //define defaults for the JFrame 
    super ("Racing"); 
    setSize(WIDTH, HEIGHT); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBackground(Color.BLACK); 

    //start the inner class 
    Move1 m1 = new Move1(); 
    m1.start(); 
} 

//draws the cars and race track 
public void paint(Graphics g) { 

    super.paint(g); 
    //draw p1 
    g.setColor(Color.RED); 
    g.fillRect(p1.x,p1.y,p1.width,p1.height); 
    g.setColor(Color.GREEN); 
    g.fillRect(foreground.x,foreground.y,foreground.width,foreground.height); 

} 
private class Move1 extends Thread implements KeyListener { 
    public void run() { 
     //makes the key listener "wake up" 
     addKeyListener(this); 

     //should be done in an infinite loop, so it repeats 
     while (true) { 
      //make try block, so it can exit if it errors 
      try { 
       //refresh screen 
       repaint(); 

       //makes car increase speed a bit 
       if (plSpeed <= 7) { 
        plSpeed += .2; 
       } 

       //lets the car stop 
       if (plSpeed==0) { 
        p1Direction = STOP; 
       } 

       //moves player based on direction 
       if (p1Direction==UP) { 
        p1.y -= (int) plSpeed; 
       } 
       if (p1Direction==DOWN) { 
        p1.y += (int) plSpeed; 
       } 
       if (p1Direction==LEFT) { 
        p1.x -= (int) plSpeed; 
       } 
       if (p1Direction==RIGHT) { 
        p1.x += (int) plSpeed; 
       } 
       if (p1Direction==STOP) { 
        plSpeed = 0; 
       } 

       //delays refresh rate 
       Thread.sleep(75); 

      } 
      catch(Exception e) { 
       //if an error, exit 
       break; 
      } 
     } 
    } 

    //have to input these (so it will compile) 
    public void keyPressed(KeyEvent event) { 
     try { 
      //makes car increase speed a bit 
      if (event.getKeyChar()=='w' || 
       event.getKeyChar()=='a' || 
       event.getKeyChar()=='s' || 
       event.getKeyChar()=='d') { 
        plSpeed += .2; 
        repaint(); 
      } 
     } catch (Exception I) {} 
    } 
    public void keyReleased(KeyEvent event) {} 

    //now, to be able to set the direction 
    public void keyTyped(KeyEvent event) { 
     if (plSpeed > 0) { 
      if (event.getKeyChar()=='a') { 
       if (p1Direction==RIGHT) { 
        p1Brake(); 
       } else { 
        if (p1Direction==LEFT) { 
        } else { 
         p1Direction = LEFT; 
        } 
       } 
      } 
      if (event.getKeyChar()=='s') { 
       if (p1Direction==UP) { 
        p1Brake(); 
       } else { 
        if (p1Direction==DOWN) { 
        } else { 
         p1Direction = DOWN; 
        } 
       } 
      } 
      if (event.getKeyChar()=='d') { 
       if (p1Direction==LEFT) { 
        p1Brake(); 
       } else { 
        if (p1Direction==RIGHT) { 
        } else { 
         p1Direction = RIGHT; 
        } 
       } 
      } 
      if (event.getKeyChar()=='w') { 
       if (p1Direction==DOWN) { 
        p1Brake(); 
       } else { 
        if (p1Direction==UP) { 
        } else { 
         p1Direction = UP; 
        } 
       } 
      } 
      if (event.getKeyChar()=='z') { 
       p1Brake(); 
      } 
     } 
    } 

    public void p1Brake() { 
     try { 
      while (plSpeed != 0) { 
       plSpeed -= .2; 
       Thread.sleep(75); 
      } 
     } catch (Exception e) { 
      plSpeed = 0; 
     } 
    } 
} 

//finally, to start the program 
public static void main(String[] args) { 
    Racing frame = new Racing(); 
    frame.setVisible(true); 
    frame.setLocationRelativeTo(null); 
    frame.setResizable(false); 
} 

}どのように点滅を防ぐことができますか?

これは私のコードのSSCCEです。私がsuper.paint(g)を追加した場合。これの上に、クラス内で、それはすべて派手になる。私がそれを残しておけば、プレイヤーを動かすたびに、プレイヤーがどこにいたのかを描き直します。私はどのようにして再塗り方を知る必要があります。

http://www.java-forums.org/awt-swing/37406-repaint-without-flashing.html

しかし、彼らは(私は前に対処したことがない、フレームにアプレットからのコードを変換するためにかなり難しいだろうと仮定した場合)アプレットを持っている:私はここにここに私の答えを得ている最も近いです。誰も私にこれを助けることができますか?

注:

私は幸せとスイングに精通していたので、私は、あなたがAWTのフレームを作ることができる知らなかったので、私は変更したくありませんでした。申し訳ありません。あなたが見ることができるように、私が描くものは何でも、プレーヤーだけではありません。

アンドリューは、ここに私のスクリーンショットです: the game

ああ、それはP2を登録しません。

+3

(whatever you named the JFrame reference).setTitle(...) が続いたJFrameの残りの部分に以下のコードを適用するように、新しいJFrameのをインスタンス化する方法、 ime。 "* [このスレッド]から(http://stackoverflow.com/questions/8889977/how-do-i-set-an-image-in-a-rectangle)。 SSCCEは表示されません。SwingやAWTが使用されているかどうかわからない、コンパイル不能なコードスニペットしか表示されません。 -1 –

+0

申し訳ありませんが、私はちょっと混乱していて、SSCCEの定義に間違っていました。私は1つのtomarrowを投稿することができるでしょう。 –

+1

これは、私の問題を示しています。 –

答えて

1

キャンバスに直接描画しようとしないで、次のフレームを常に準備しておき、古いものと交換するバックグラウンドスレッドを使用しないでください。

while (state == RUNNING) 
    { 
     long beforeTime = System.nanoTime(); 
     gEngine.update(); // update stuff like game score life etc.. 

     Canvas c = null; 
     try 
     { 
      c = mSurfaceHolder.lockCanvas(null); 
      synchronized (mSurfaceHolder) 
      {     
       drawable.setBounds(0, 0, 800, 600); 
       drawable.draw(c); // flash new background if required for the new frame 
       gEngine.draw(c); // update game state 
      } 
     } finally 
     { 
      if (c != null) 
      { 
       mSurfaceHolder.unlockCanvasAndPost(c); 
      } 
     } 

     this.sleepTime = delay 
       - ((System.nanoTime() - beforeTime)/1000000L); 

     try 
     { 
      if (sleepTime > 0) 
      { 
       Thread.sleep(sleepTime); 
      } 
     } catch (InterruptedException ex) 
     { 
      Logger.getLogger(PaintThread.class.getName()).log(Level.SEVERE, 
        null, ex); 
     } 

    } 
} 
+0

aahhh良いアイデア。今、それをどうやって行うかを理解する。私はそれで眠り、明日あなたに戻ってきます。 –

+1

問題は、これはAWTコードの提案で、スウィングでは動作しません。これはポスターの最後の質問に基づいています。ポストがSSCCEの投稿を学ぶまで、彼の最後の投稿にも勧められました。私たちはちょうど推測しています。ポスターは彼の質問で参照した投稿からペイントコードをコピーしていない。 – camickr

+0

ペイントとは唯一違うのは、私の質問で言及していた "super.paint(g)"という行を追加して、私のコードに再び入れる価値があるとは思わなかったということです。ペイントコードを残さずにできるだけ少ないと思いました。これに少し混乱があるように見えます - 私はスイングを使用しています。 –

3

Racing UI

私は変更の数を作りました。ここに私が思い出すことのできるものがあります。

  1. JPanelにトップレベルのコンテナからカスタムペイントをリファクタリングし、paintComponent()に絵を動かしました。
  2. 削除されたThreadおよびThread.sleep(n) &は、Timer/ActionListenerで置き換えられました。
  3. EDTにGUIを構築しました。
  4. JFrameのサイズを削除しました。代わりに、JPanel(実際の描画領域)に適したサイズを設定し、正しい全体サイズを取得するためにJFrame.pack()を呼び出します。
  5. very splash-screen likesetLocationRelativeTo(null)の代わりにsetLocationByPlatform(true)を使用してください。

さらなるヒントについては、コードを慎重に確認してください。

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Racing extends JPanel implements KeyListener { 
private static final long serialVersionUID = -198172151996959655L; 

//keeps track of player speed 
double plSpeed = .5; 

//numbers that represent direction 
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, STOP = 5, START = 6; 

//keeps track of player direction 
int p1Direction = START; 

//makes player 1's car 
Rectangle p1 = new Rectangle (100, 25, 30, 30); 

//constructor 
public Racing() { 
    //define defaults for the JFrame 
    setBackground(Color.BLACK); 

    //makes the screen size 
    setPreferredSize(new Dimension(400,50)); 

    //makes the key listener "wake up" 
    addKeyListener(this); 
    setFocusable(true); 

    ActionListener al = new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      //refresh screen 
      repaint(); 

      //makes car increase speed a bit 
      if (plSpeed <= 7) { 
       plSpeed += .2; 
      } 

      //lets the car stop 
      if (plSpeed==0) { 
       p1Direction = STOP; 
      } 

      //moves player based on direction 
      if (p1Direction==UP) { 
       p1.y -= (int) plSpeed; 
      } 
      if (p1Direction==DOWN) { 
       p1.y += (int) plSpeed; 
      } 
      if (p1Direction==LEFT) { 
       p1.x -= (int) plSpeed; 
      } 
      if (p1Direction==RIGHT) { 
       p1.x += (int) plSpeed; 
      } 
      if (p1Direction==STOP) { 
       plSpeed = 0; 
      } 
     } 
    }; 

    Timer t = new Timer(75,al); 
    t.start(); 
} 

//draws the cars and race track 
@Override 
public void paintComponent(Graphics g) { 

    super.paintComponent(g); 
    //draw p1 
    g.setColor(Color.RED); 
    g.fillRect(p1.x,p1.y,p1.width,p1.height); 

} 

//have to input these (so it will compile) 
public void keyPressed(KeyEvent event) { 
    System.out.println(event); 
    try { 
     //makes car increase speed a bit 
     if (event.getKeyChar()=='w' || 
      event.getKeyChar()=='a' || 
      event.getKeyChar()=='s' || 
      event.getKeyChar()=='d') { 
       plSpeed += .2; 
       //repaint(); 
     } 
    } catch (Exception I) {} 
} 
public void keyReleased(KeyEvent event) {} 

//now, to be able to set the direction 
public void keyTyped(KeyEvent event) { 
    if (plSpeed > 0) { 
     if (event.getKeyChar()=='a') { 
      if (p1Direction==RIGHT) { 
       p1Brake(); 
      } else { 
       if (p1Direction==LEFT) { 
       } else { 
        p1Direction = LEFT; 
       } 
      } 
     } 
     if (event.getKeyChar()=='s') { 
      if (p1Direction==UP) { 
       p1Brake(); 
      } else { 
       if (p1Direction==DOWN) { 
       } else { 
        p1Direction = DOWN; 
       } 
      } 
     } 
     if (event.getKeyChar()=='d') { 
      if (p1Direction==LEFT) { 
       p1Brake(); 
      } else { 
       if (p1Direction==RIGHT) { 
       } else { 
        p1Direction = RIGHT; 
       } 
      } 
     } 
     if (event.getKeyChar()=='w') { 
      if (p1Direction==DOWN) { 
       p1Brake(); 
      } else { 
       if (p1Direction==UP) { 
       } else { 
        p1Direction = UP; 
       } 
      } 
     } 
     if (event.getKeyChar()=='z') { 
      p1Brake(); 
     } 
    } 
} 

public void p1Brake() { 
    try { 
     while (plSpeed != 0) { 
      plSpeed -= .2; 
     } 
    } catch (Exception e) { 
     plSpeed = 0; 
    } 
} 

//finally, to start the program 
public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      JFrame f = new JFrame("Racing"); 
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      f.add(new Racing()); 
      f.pack(); 
      f.setLocationByPlatform(true); 
      f.setResizable(false); 
      f.setVisible(true); 
     } 
    }); 
} 
} 
+0

オハイオ州と私は混乱しているもう一つのことがあります:EDTとは何ですか? –

+0

さて、私はこれらの変更を自分のゲームコードに実装しました。残念ながら、古いコードを保存するのを忘れてしまいました。私はまだ同じトレイルを取得しますが、コンピュータは長方形が重複していることを認識せず、スピードはすべて台無しです。あなたが興味があるなら、私はあなたに私の完全な現在のコードを送ることができます。私はそれのスクリーンショットを私の質問に入れています。 –

0

コードをアプレットからJFrameに変更することはまったく難しくありません。 のJPanelにクラスの拡張子の名前を変更します。

public class Racing extends JPanel

を、あなたが新しいレーシングは新しいJFrameの 、今までエラーの動きをスローsetTitle(...)のようなレースで任意のメソッドをインスタンス化し、それを変更 インスタンス化する方法に*「私は次のトンそれを行うすることを確認しますために何が起こった

JFrame.add(new Racing()); 
JFrame.setSize(*the size of Racing window*); 
関連する問題