2015-02-01 2 views
3

유니 (uni)를위한 임무가 주어졌으며 사용자가 방향키를 사용하여 게임을 제어 할 수 있도록해야합니다.자바 키 바인딩

지금까지 다음과 같은 사항이 있지만 작동하지 않습니다. 제가 빠진 것이 명백합니까?

// key bindings 

    // add the key bindings for up, down, left and right to the input map 
    gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0), "down"); 
    gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0), "up"); 
    gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0), "left"); 
    gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0), "right"); 

    // assign actions to the key bindings in the action map 
    gamePanel.getActionMap().put("down", new AbstractAction() 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      move("DOWN"); 
     } 
    }); 
    gamePanel.getActionMap().put("up", new AbstractAction() 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      move("UP"); 
     } 
    }); 
    gamePanel.getActionMap().put("left", new AbstractAction() 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      move("LEFT"); 
     } 
    }); 
    gamePanel.getActionMap().put("right", new AbstractAction() 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      move("RIGHT"); 
     } 
    }); 

방향 버튼 중 하나를 누르면 아무 일도 일어나지 않습니다.

미리 도움을 주셔서 감사합니다.

MCVE은 첫 번째 below- 나는 충분히 여부를

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 
import javax.swing.event.*; 

import com.sun.java.swing.plaf.windows.resources.windows; 

import java.util.ArrayList; 

public class MCVE extends JFrame 
{ 
    // Game panel 
    private JPanel gamePanel; 

    private Container window; 

    public static void main(String[] args) 
    { 
     MCVE frame = new MCVE(); 

     frame.setSize(1000,700); 

     frame.createGUI(); 

     frame.setLocationRelativeTo(null); 

     frame.setVisible(true); 
    } 

    private void createGUI() 
    { 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     window = getContentPane(); 

     gamePanel = new JPanel(); 


     window.add(gamePanel); 
    } 

    private void keyBindings() 
    { 
     // key bindings 

     // add the key bindings for up, down, left and right to the input map 
     gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0), "down"); 
     gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0), "up"); 
     gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0), "left"); 
     gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0), "right"); 

     // assign actions to the key bindings in the action map 
     gamePanel.getActionMap().put("down", new AbstractAction() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       System.out.println("down"); 
      } 
     }); 
     gamePanel.getActionMap().put("up", new AbstractAction() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       System.out.println("up"); 
      } 
     }); 
     gamePanel.getActionMap().put("left", new AbstractAction() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       System.out.println("left"); 
      } 
     }); 
     gamePanel.getActionMap().put("right", new AbstractAction() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       System.out.println("right"); 
      } 
     }); 
    } 
} 
+2

디버깅하면 어떻게됩니까? 'move (...) '메소드는 무엇을 하는가? 디버깅 해 봤어? 실행하고 테스트 할 수있는 [최소 예제 프로그램] (http://stackoverflow.com/help/mcve)은 어디에 있습니까? –

+0

게임을 제어하고 동일한 방법을 사용하는 JButton이 있으므로이 방법은 완벽하게 작동합니다 – ryansin

+1

.. MCVE는 어디에 있습니까? –

답변

5

귀하의 실행 가능한 예제는 결코 keyBindings 메소드를 호출하지, 그래서 그들은 등록되지 않습니다. 무언가가 작동하지 않으면 항상 제대로 설정했는지 항상 확인하십시오. 항상 이런 종류의 실수를합니다.)

그리고이 경우에는 onKeyRelease 매개 변수를 사용하여 릴리스 이벤트 및 num-pad 화살표 키 지원

import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.ActionMap; 
import javax.swing.InputMap; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.KeyStroke; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Test { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public Test() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private JLabel up; 
     private JLabel down; 
     private JLabel left; 
     private JLabel right; 

     public TestPane() { 

      up = createLabel("UP"); 
      down = createLabel("DOWN"); 
      left = createLabel("LEFT"); 
      right = createLabel("RIGHT"); 

      setLayout(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 1; 
      gbc.gridy = 0; 
      gbc.fill = GridBagConstraints.BOTH; 
      gbc.anchor = GridBagConstraints.CENTER; 
      add(up, gbc); 
      gbc.gridy = 2; 
      add(down, gbc); 

      gbc.gridx = 0; 
      gbc.gridy = 1; 
      add(left, gbc); 
      gbc.gridx = 2; 
      add(right, gbc); 

      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up-press", new HighlightAction(up, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0, false), "up-press", new HighlightAction(up, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down-press", new HighlightAction(down, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0, false), "down-press", new HighlightAction(down, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left-press", new HighlightAction(left, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0, false), "left-press", new HighlightAction(left, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right-press", new HighlightAction(right, true)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0, false), "right-press", new HighlightAction(right, true)); 

      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up-release", new HighlightAction(up, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0, true), "up-release", new HighlightAction(up, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down-release", new HighlightAction(down, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0, true), "down-release", new HighlightAction(down, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "left-release", new HighlightAction(left, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0, true), "left-release", new HighlightAction(left, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "right-release", new HighlightAction(right, false)); 
      registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0, true), "right-release", new HighlightAction(right, false)); 
     } 

     public void registerKeyBinding(KeyStroke keyStroke, String name, Action action) { 
      InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); 
      ActionMap am = getActionMap(); 

      im.put(keyStroke, name); 
      am.put(name, action); 
     } 

     public JLabel createLabel(String text) { 
      JLabel label = new JLabel(text); 
      label.setOpaque(true); 
      label.setHorizontalAlignment(JLabel.CENTER); 
      return label; 
     } 

     public class HighlightAction extends AbstractAction { 

      private JLabel label; 
      private boolean on; 

      public HighlightAction(JLabel label, boolean on) { 
       this.label = label; 
       this.on = on; 
      } 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (on) { 
        label.setBackground(Color.RED); 
        label.repaint(); 
       } else { 
        label.setBackground(null); 
       } 
      } 

     } 

    } 

} 
+0

아, 도움을 많이 주셔서 감사합니다. – ryansin

+0

도움이 되니 기쁘다. 실제 문제가되기를 바랍니다.) – MadProgrammer

+0

그래, 다시 한 번 감사드립니다. – ryansin

1

JPanel과 좋은 경우 알려 그렇게 한 WHEN_FOCUSED 왼쪽 및 오른쪽 화살표 키 정의 키 바인딩. 나는 어떤 행동이 정의되었는지는 모르지만 그것은 내 행동이 아닙니다. 그래서 WHEN_FOCUSED 키 바인딩과 WHEN_IN_FOCUSED_WINDOW 키 바인딩을 화살표 키에 정의했습니다.

내 키 바인딩 방법은 다음과 같습니다. 원하는 경우 WASD 키를 무시할 수 있습니다.

private void createGUI() { 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    window = getContentPane(); 
    gamePanel = new JPanel(); 
    window.add(gamePanel); 
    // This is going to help... 
    keyBindings(); 
} 

이 어디 디버그 문 및 도움이 될 것입니다 코드를 디버깅 시간의 작은 금액을 투자 ...

private void setKeyBindings() { 
     InputMap inputMap = 
       gridPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW); 
     inputMap.put(KeyStroke.getKeyStroke("W"), "up arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("S"), "down arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("A"), "left arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("D"), "right arrow"); 

     inputMap.put(KeyStroke.getKeyStroke("UP"), "up arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("DOWN"), "down arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("LEFT"), "left arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "right arrow"); 

     inputMap = gridPanel.getInputMap(JPanel.WHEN_FOCUSED); 
     inputMap.put(KeyStroke.getKeyStroke("UP"), "up arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("DOWN"), "down arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("LEFT"), "left arrow"); 
     inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "right arrow"); 


     gridPanel.getActionMap().put("up arrow", 
       new UpArrowAction(this, model)); 
     gridPanel.getActionMap().put("down arrow", 
       new DownArrowAction(this, model)); 
     gridPanel.getActionMap().put("left arrow", 
       new LeftArrowAction(this, model)); 
     gridPanel.getActionMap().put("right arrow", 
       new RightArrowAction(this, model)); 
    } 
+0

모든 FOCUS에서'JPanel'에 이전에 등록 된 키 바인딩을 확인하고 찾았습니다 레벨 – MadProgrammer

+0

2014 년 3 월 Java 7에서이 메소드를 작성했습니다. 아마도 Java 8에서 키 바인딩이 변경되었을 것입니까? –

+0

아니요, Java를 사용하여 테스트했습니다. – MadProgrammer