2014-05-16 9 views
0

그래서이 화살표 키에 따라 파란색 사각형을 움직이는 프로그램을 만들었습니다. 그러나 몇 가지 문제점이 있습니다 (코드에서 보게 될 것입니다). 나는 웹상에서 대답을 찾았지만 아무런 답도 찾지 못했다. 내 문제는 다음과 같습니다.Java ArrowKey Listener

  • 위치를 이동하고 유지하려는 반면 코드는 시작 위치로 재설정합니다. 나는 이것을 어리 석었지만 그것을 고칠 수 없었다.
  • 한 번에 한 방향이 아닌 모든 방향으로 대각선으로 이동할 수 있기를 원하기 때문에 이동 중에 방향을 바꿀 수있는 능력이 있습니다.
  • 이동 키를 누르고 싶습니다. 문제가 위에서 설명한 유체 운동과 함께
  • 을하지 않는 것 그것은, 나는 또한 (너무 많은 키를 누르고 있으면 증가) 포물선과 같은 방식으로 이동하지하려고 노력하고 있어요 .

논리적 인 문제가 있거나 자바를 구현하는 간단한 방법이 있습니다. 그렇다면 명시적인 설명을 남겨 두십시오. 내가 여기 저기 적어 놓은 임의의 음표를 무시하십시오.

//graham 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.util.ArrayList; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

class Arrows extends JPanel implements KeyListener { 
private int c = 0, c1 = 0; 
private int x = 250; 
private int y = 250; 
private int cx = 0; //change in x 
private int cy = 0; //change in y 
private static ArrayList<Integer> keys = new ArrayList<Integer>(); 


public Arrows() { 
    this.setPreferredSize(new Dimension(500, 500)); 
    addKeyListener(this); 
} 

public void addNotify() { 
    super.addNotify(); 
    requestFocus(); 
} 

public void paintComponent(Graphics g) { 

    //********* 
    //here need to repaint according to the key 
    //need to update to make so can press (and hold) multiple different keys at once 
    //********* 

    g.setColor(Color.WHITE); 
    g.fillRect(x, y , 20, 20); 
    //for(int i = 0; i < keys.size(); i++){ //********> only want to handle one at a time 
     //handle the key 

     //***Should move this to somewhere else, so repaint after update stuff in keyPressed 

    //} 
    //x += cx; 
    //y += cy; 
    g.setColor(Color.BLUE); 
    g.fillRect(x + cx, y + cy, 20, 20); 
} 



public void keyPressed(KeyEvent e) { 
    //****** 
    //need to add to the keyList here 
    //might want to use bitset 
    //****** 
    //keys.add(e.getKeyCode()); 
    //********************************** 
    //c = keys.get(0); 
    c = e.getKeyCode(); 
     switch(c){ 
     case 37: 
      //left arrow 
      cx -= 3; 
      //keys.remove(0); 
      break; 
     case 38: 
      // up arrow 
      cy -= 3; 
      //keys.remove(0); 
      break; 
     case 39: 
      //right arrow 
      cx += 3; 
      //keys.remove(0); 
      break; 
     case 40: 
      //down arrow 
      cy += 3; 
      //keys.remove(0); 
      break; 
     } 
     //********************************** 
    repaint(); 
} 
public void keyReleased(KeyEvent e) { 
    //**** 
    //here need to remove key fromt he list, and may want to fix teleportation.. 
    //**** 

    //set the change values to 0 
    c1 = e.getKeyCode(); 
    switch(c1){ 
    case 37: 
     //left arrow 
     cx = 0; 
     break; 
    case 38: 
     // up arrow 
     cy = 0; 
     break; 
    case 39: 
     //right arrow 
     cx = 0; 
     break; 
    case 40: 
     //down arrow 
     cy = 0; 
     break; 
    } 
    repaint(); 
} 
public void keyTyped(KeyEvent e) { 
} 

public static void main(String[] s) { 
    JFrame f = new JFrame(); 
    f.getContentPane().add(new Arrows()); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.pack(); 
    f.setVisible(true); 

    //need to null out keys 
    keys.add(65); 

    //here want to update every time through constant time accoridng to the keypressed  and ereleased crap 

    //repaint(); 
} 
} 

답변

-1

일부 일반 프로그래밍 의견 :

  1. 가 requestFocus를 사용하지 마십시오(). 해당 방법에 대한 API를 읽고 더 나은 방법을 제안 할 것입니다.
  2. 마법 번호를 사용하지 마십시오. 37, 38, 39, 40은 아무 의미도 없습니다. 적절한 KeyEvent.vK ... 변수를 사용하십시오.

는 모든 KeyListener를 사용하지 마십시오. 스윙은 Key Bindings과 함께 사용하도록 설계되었습니다. 자세한 내용 및 작업 예제는 Motion Using the Keyboard을 참조하십시오.

+0

덕분에, 이것은 아마도 아직 내가 (다른 사람과는 달리 실제로는 거의 의미가) 키 바인딩에서 본 가장 유용한 튜토리얼입니다. – Kemosabe