Computer_IT/JAVA

[JAVA5] 방향키를 이용해 button 움직이기

고급코드 2006. 9. 14. 14:37
반응형
방향키를 이용해 button 움직이기

파일명 : KeyEvent1.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. public class KeyEvent1 extends Frame {
  4.   Button man;
  5.   public KeyEvent1(String title) {
  6.     super(title);
  7.     setLayout(null);
  8.     this.setSize(200, 200);
  9.    
  10.     man = new Button("Man");
  11.     man.setBounds(100, 100, 40, 20);
  12.     man.setBackground(Color.BLUE);
  13.     man.setForeground(Color.WHITE);
  14.     this.add(man);
  15.     man.addKeyListener(new KeyHandler());
  16.   }
  17.   public static void main(String args[]) {
  18.     KeyEvent1 me = new KeyEvent1(" Key 이벤트 활용 ");
  19.     me.setVisible(true);
  20.   }
  21.   class KeyHandler extends KeyAdapter {
  22.     public void keyPressed(KeyEvent e) {
  23.       String direction = e.getKeyText(e.getKeyCode());
  24.       System.out.println(direction);
  25.       int x=man.getX();
  26.       int y=man.getY();
  27.      
  28.       if(direction.equals("Right")) x+=10;
  29.       else if(direction.equals("Left")) x-=10;
  30.       else if(direction.equals("Down")) y+=10;
  31.       else if(direction.equals("Up")) y-=10;
  32.      
  33.       man.setLocation(x, y);
  34.     }
  35.   }
  36. }
 
반응형