2016-09-20 71 views
0

我很困惑爲什麼這段代碼不會讓第二個球移動。我的目標是擁有兩個球,而你正在控制其中一個,另一個只是隨機彈跳。現在我被卡在箭頭鍵球上。我不明白爲什麼它不通過箭頭鍵移動。JAVA爲什麼我的第二圈移動箭頭鍵

import java.awt.*; 
import java.awt.event.KeyEvent; 
import java.util.Formatter; 
import javax.swing.*; 

/** 
* One ball bouncing inside a rectangular box. 
* All codes in one file. Poor design! 
*/ 
// Extends JPanel, so as to override the paintComponent() for custom rendering codes. 
public class Man extends JPanel { 
    // Container box's width and height 
    private static final int BOX_WIDTH = 640; 
    private static final int BOX_HEIGHT = 480; 

    private boolean upPressed = false; 
    private boolean downPressed = false; 
    private boolean leftPressed = false; 
    private boolean rightPressed = false; 

    // Ball's properties 
    private float ballRadius = 20; // Ball's radius 
    private float ballX = ballRadius + 50; // Ball's center (x, y) 
    private float ballY = ballRadius + 20; 
    private float ballSpeedX = 3; // Ball's speed for x and y 
    private float ballSpeedY = 2; 

    // ball # 2 
    public float ballSpeedX2 = 0; 
    public float ballSpeedY2 = 0; 
    private float ball2Radius = 20; // Ball's radius 
    private float ball2X = 320; // Ball's center (x, y) 
    private float ball2Y = 240; 

    private static final int UPDATE_RATE = 30; // Number of refresh per second 

    /** Constructor to create the UI components and init game objects. */ 
    public Man() { 
     this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT)); 

    // Start the ball bouncing (in its own thread) 
    Thread gameThread = new Thread() { 
    public void step(){ 
     ball2X += ballSpeedX2; 
     ball2Y += ballSpeedY2; 

     if (rightPressed) { 
      ballSpeedX2+=5; 
     } 

     if (leftPressed) { 
      ballSpeedX2-=5; 
     } 

     if (upPressed) { 
      ballSpeedY2-=5; 
     } 

     if (downPressed) { 
      ballSpeedY2+=5; 
     } 

     repaint(); 
     try { 
      Thread.sleep(1000/UPDATE_RATE); // milliseconds 
     } catch (InterruptedException ex) { } 
    } 

    public void run() { 
     while (true) { 
      // Execute one update step 
      // Calculate the ball's new position 
      ballX += ballSpeedX; 
      ballY += ballSpeedY; 
      // Check if the ball moves over the bounds 
      // If so, adjust the position and speed. 
      if (ballX - ballRadius < 0) { 
       ballSpeedX = -ballSpeedX; // Reflect along normal 
       ballX = ballRadius; // Re-position the ball at the edge 
      } else if (ballX + ballRadius > BOX_WIDTH) { 
       ballSpeedX = -ballSpeedX; 
       ballX = BOX_WIDTH - ballRadius; 
      } 

      // May cross both x and y bounds 
      if (ballY - ballRadius < 0) { 
       ballSpeedY = -ballSpeedY; 
       ballY = ballRadius; 
      } else if (ballY + ballRadius > BOX_HEIGHT) { 
       ballSpeedY = -ballSpeedY; 
       ballY = BOX_HEIGHT - ballRadius; 
      } 

      // Refresh the display 
      repaint(); // Callback paintComponent() 
      // Delay for timing control and give other threads a chance 

      try { 
       Thread.sleep(1000/UPDATE_RATE); // milliseconds 
      } catch (InterruptedException ex) { } 
     } 
    } 
}; 

在後面的代碼:

gameThread.start(); // Callback run() 
} 

/** Custom rendering codes for drawing the JPanel */ 
    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); // Paint background 

     // Draw the box 
     g.setColor(Color.BLACK); 
     g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT); 

     // Draw the ball 
     g.setColor(Color.BLUE); 
     g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius), 
     (int)(2 * ballRadius), (int)(2 * ballRadius)); 

     // Display the ball's information 
     g.setColor(Color.WHITE); 
     g.setFont(new Font("Courier New", Font.PLAIN, 12)); 

     StringBuilder sb = new StringBuilder(); 

     Formatter formatter = new Formatter(sb); 
     formatter.format("Ball @(%3.0f,%3.0f) Speed=(%2.0f,%2.0f)", ballX, ballY, 
     ballSpeedX, ballSpeedY); 
     g.drawString(sb.toString(), 20, 30); 
     g.setColor(Color.BLUE);  

     g.fillOval((int) (ball2X - ball2Radius), (int) (ball2Y - ball2Radius), 
     (int)(2 * ball2Radius), (int)(2 * ball2Radius)); 

     g.setColor(Color.RED); 
     g.setFont(new Font("Courier New", Font.PLAIN, 12)); 
     g.drawString(sb.toString(), 20, 30); 
     g.setColor(Color.GREEN); 
    }  

    public void keyPressed(KeyEvent e) {     

     if (e.getKeyCode() == KeyEvent.VK_RIGHT) { 
      rightPressed = true; 
     } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { 
      leftPressed = true; 
     } else if (e.getKeyCode() == KeyEvent.VK_UP) { 
      upPressed = true; 
     } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { 
      downPressed = true; 
     } 

     repaint(); 

     try { 
      Thread.sleep(1000/UPDATE_RATE); // milliseconds 
     } catch (InterruptedException ex) { } 
    } 

    public void keyReleased(KeyEvent e) { 
     if (e.getKeyCode() == KeyEvent.VK_RIGHT) { 
      rightPressed = false; 
     } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { 
      leftPressed = false; 
     } else if (e.getKeyCode() == KeyEvent.VK_UP) { 
      upPressed = false; 
     } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { 
      downPressed = false; 

      try { 
       Thread.sleep(1000/UPDATE_RATE); // milliseconds 
      } catch (InterruptedException ex) { } 
     } 
    } 

    public void keyTyped(KeyEvent e) {}  

    /** main program (entry point) */ 
    public static void main(String[] args) { 
     // Run GUI in the Event Dispatcher Thread (EDT) instead of main thread. 

     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       // Set up main window (using Swing's Jframe) 
       JFrame frame = new JFrame("A Bouncing Ball"); 

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setContentPane(new Man()); 
       frame.pack(); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 
+1

如果您將代碼縮減爲您認爲應該幫助您實現的部分並添加一些更詳細的說明,它將會很好。 – ChiefTwoPencils

+0

你在代碼中使用'keyPressed()','keyReleased()'方法的地方? – DimaSan

+0

[如何使用密鑰綁定而不是密鑰監聽器]的可能重複(http://stackoverflow.com/questions/22741215/how-to-use-key-bindings-instead-of-key-listeners) – user1803551

回答

-1

我修改你的代碼了一下,我刪除了某些非相關的第二球的移動,所以你可以看到它是如何工作的,再加上我不想給你一個完整的答案,你將不得不先了解發生了什麼,並相應地修改你的當前代碼。

首先 - 你需要一個KeyListener。名稱不言自明,它聽取鍵盤點擊。你在課堂上通過implements KeyListener。然後,您需要將該偵聽器添加到您的框架中 - frame.addKeyListener(cat)在我的代碼中。然後你需要在run方法(ball2X += ballSpeedX2等)中實際移動球內循環。同樣在你的代碼中,你基本上在任何地方都會延遲 - 這不是一個好主意,它們會阻止一切。在你的代碼中,你有一個step方法,你不會在任何地方調用它 - 修改它,並在run方法中調用它,或者只需要將所有代碼放在run方法中。如果您希望球只在點擊時移動(1次點擊--1次移動,不放),然後在將位置設置爲0之後將其移動到0.如果您想在keyRelease的持續按鍵設置速度爲0時移動它,但要小心,如果你同時左右舉行,該怎麼辦?你需要照顧這一點。確定這裏是代碼,我基本上移動了一些行,添加了5行(用於KeyListener),並刪除了與第二個球無關的代碼,這是98%的代碼。

btw。我把班級名稱改爲Cat,所以把它放在Cat.java不是Man.java

import java.awt.*; 
import java.awt.event.KeyEvent; 
import java.util.Formatter; 
import javax.swing.*; 
import java.awt.event.*; 
public class Cat extends JPanel implements KeyListener { 

    private static final int BOX_WIDTH = 640; 
    private static final int BOX_HEIGHT = 480; 
    private float ballSpeedX2 = 0; 
    private float ballSpeedY2 = 0; 
    private float ball2Radius = 20; 
    private float ball2X = 120; 
    private float ball2Y = 140; 

    private static final int UPDATE_RATE = 30; 

    public Cat() { 
     this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT)); 
     Thread gameThread = new Thread() { 
      public void run() { 
       while (true) { 
        ball2X += ballSpeedX2; 
        ball2Y += ballSpeedY2; 
        if (ball2X - ball2Radius < 0) { 
         ballSpeedX2 = -ballSpeedX2; 
         ball2X = ball2Radius; 
        } else if (ball2X + ball2Radius > BOX_WIDTH) { 
         ballSpeedX2 = -ballSpeedX2; 
         ball2X = BOX_WIDTH - ball2Radius; 
        } 

        if (ball2Y - ball2Radius < 0) { 
         ballSpeedY2 = -ballSpeedY2; 
         ball2Y = ball2Radius; 
        } else if (ball2Y + ball2Radius > BOX_HEIGHT) { 
         ballSpeedY2 = -ballSpeedY2; 
         ball2Y = BOX_HEIGHT - ball2Radius; 
        } 
        repaint(); 
        try { 
         Thread.sleep(1000/UPDATE_RATE); 
        } catch (InterruptedException ex) { } 
       } 
      } 
     }; 
     gameThread.start(); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.BLACK); 
     g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT); 
     g.setColor(Color.BLUE); 
     g.fillOval((int) (ball2X - ball2Radius), (int) (ball2Y - ball2Radius), 
        (int)(2 * ball2Radius), (int)(2 * ball2Radius)); 
    } 

    public void keyPressed(KeyEvent e) { 
     if (e.getKeyCode() == KeyEvent.VK_RIGHT) { 
      ballSpeedX2 = 5; 
     } 
     else if (e.getKeyCode() == KeyEvent.VK_LEFT) { 
      ballSpeedX2 = -5; 
     } 
     else if (e.getKeyCode() == KeyEvent.VK_UP) { 
      ballSpeedY2 = -5; 
     } 
     else if (e.getKeyCode() == KeyEvent.VK_DOWN) { 
      ballSpeedY2 = 5; 
     } 
    } 

    public void keyReleased(KeyEvent e) { } 
    public void keyTyped(KeyEvent e) { } 

    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new JFrame("A Bouncing Ball"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       Cat cat = new Cat(); 
       frame.setContentPane(cat); 
       frame.pack(); 
       frame.addKeyListener(cat); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 
+0

@JulianJacobs這不是一個好的解決方案。請參閱我給你的問題的鏈接。 – user1803551