2012-06-23 68 views
4

我有一些我需要修改的代碼。在代碼中,原作者使用KeyStroke.getKeyStroke來進行用戶輸入。例如,在此代碼中,他使用a而不是左箭頭。Java:使用箭頭鍵擊鍵

我想改變這一點,但我不知道如何。

這裏是原代碼:

registerKeyboardAction(
     new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       tick(RIGHT); 
      } 
     }, "right", KeyStroke.getKeyStroke('d'), WHEN_IN_FOCUSED_WINDOW 
); 

我必須將它更改爲這樣的事情,但在運行時,它不工作: KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT);

KeyStroke.getKeyStroke("RIGHT");

+0

我認爲['registerKeyboardAction的()'](http://docs.oracle.com/javase/1.3/docs/api/javax/swing/JComponent.html )已經過時了一段時間。 –

回答

6

通過按DOWNARROW KEY來啓動程序,首先要看字符串。這裏有一個看看這個例子程序:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class KeyBindingExample 
{ 
    private void createAndDisplayGUI() 
    { 
     JFrame frame = new JFrame("Key Binding Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     DrawingPanel contentPane = new DrawingPanel(); 
     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
     contentPane.requestFocusInWindow(); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new KeyBindingExample().createAndDisplayGUI(); 
      } 
     }); 
    } 
} 

class DrawingPanel extends JPanel 
{ 
    private int x; 
    private int y; 
    private String[] commands = { 
            "UP", 
            "DOWN", 
            "LEFT", 
            "RIGHT" 
           };      

    private ActionListener panelAction = new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent ae) 
     { 
      String command = (String) ae.getActionCommand(); 
      if (command.equals(commands[0])) 
       y -= 1;    
      else if (command.equals(commands[1])) 
       y += 1; 
      else if (command.equals(commands[2])) 
       x -= 1; 
      else if (command.equals(commands[3])) 
       x += 1; 

      repaint(); 
     } 
    }; 

    public DrawingPanel() 
    { 
     x = 0; 
     y = 0; 

     for (int i = 0; i < commands.length; i++)  
      registerKeyboardAction(panelAction, 
          commands[i], 
          KeyStroke.getKeyStroke(commands[i]), 
          JComponent.WHEN_IN_FOCUSED_WINDOW); 
    } 

    @Override 
    public Dimension getPreferredSize() 
    { 
     return (new Dimension(500, 300)); 
    } 

    @Override 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     String displayText = "X : " + x + " and Y : " + y; 
     System.out.println(displayText); 
     g.drawString(displayText, x, y); 
    } 
} 
5

你應該能夠使用KeyStroke.getKeyStroke("DOWN");,"UP","LEFT","RIGHT",做你想做的。

有關更多詳細信息,請參閱javadoc

+0

我忘了在本文中加入這個案例。沒有錯誤,但仍然無法正常工作。 :( – hqt

+0

@hqt whats'tick(RIGHT);',因爲在我的代碼中爲我工作,爲了更好地幫助更快地發佈[SSCCE](http://sscce.org/) – mKorbel

+0

+1,這確實起作用: - ) –