2016-02-12 61 views
0

我有這個程序,當按箭頭鍵時,它超過了框架。但是,我希望形狀在超出邊界時反彈回來。誰可以幫我這個事。如何避免形狀超過java框架的邊框

{ 
    JFrame frame = new JFrame("PacMan"); 
    PacManObject panel = new PacManObject(); 
    panel.setFocusable(true); 
    panel.setRequestFocusEnabled(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600,600); 
    frame.setVisible(true); 

    frame.add(panel); 
    panel.addKeyListener(panel); 


} 

public static void main(String[] args) { 
    Runnable runnable = new Runnable(){ 

     @Override 
     public void run() { 
      new PacMan(); 
     } 

    };EventQueue.invokeLater(runnable); 
} 

class PacManObject extends JPanel implements KeyListener{ 

    private int xLocation = 100; 
    private int yLocation = 100; 
    private int mouth = 280; 
    private int angle = 45; 
    private int xrandomLocation = 300; 
    private int yrandomLocation = 400; 
    private int xLocationEyes = 115; 
    private int yLocationEyes = 115; 

當我畫我的形狀

@Override 
    public void paintComponent(Graphics graphics) 
    { 
     super.paintComponent(graphics); 

     //pacman 
     graphics.setColor(Color.yellow); 
     graphics.fillArc(xLocation, yLocation, 100, 100, angle, mouth); 

     //eyes 
     graphics.setColor(Color.BLACK); 
     graphics.fillOval(xLocationEyes, yLocationEyes, 20, 20); 
     food(graphics); 
    } 

當按下方向鍵

@Override 
    public void keyPressed(KeyEvent keyboard) { 

     int keyboardPress = keyboard.getKeyCode(); 
     if(keyboardPress == KeyEvent.VK_RIGHT){ 
      xLocation += 30; 
      xLocationEyes += 30; 
      angle = 45; 
      repaint(); 
     } 
     else if(keyboardPress == KeyEvent.VK_LEFT){ 

      angle = -145; 
      xLocation -= 30; 
      xLocationEyes -= 30; 
      repaint(); 
     } 
    } 

回答

3

放在距離檢查它採用類似

if (xLocation + 100 >= getWidth()) { 
    xLocation = getWidth() - 100; 
} else if (xLocation < 0) { 
    xLocation = 0; 
} 

你應該這樣做同樣的事情

一般來說,你應該有一個主/遊戲循環,負責更新遊戲的當前狀態(基於輸入和其他要求的當前狀態(如幽靈的AI))和時間表更新到用戶界面。

這樣,您可以在您的密鑰處理程序中設置一個標記,主/遊戲循環將檢查哪個標記,更新播放器的狀態以及重新繪製時間表。這克服了第一次按鍵事件和重複事件之間的延遲的固有問題。

我也考慮使用KeyListener以上的密鑰綁定API。

也許,看看How to Use Key BindingsHow to use Swing TimersHow to eliminate delay in keyPress?一些更多的想法