Java:使用带箭头键的击键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11171021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Use keystroke with arrow key
提问by hqt
I have some code that I need to modify. In the code, the original author uses KeyStroke.getKeyStroke
to take user input. In this code, for example, he uses a
instead of left arrow.
我有一些代码需要修改。在代码中,原作者用于KeyStroke.getKeyStroke
获取用户输入。例如,在此代码中,他使用a
代替左箭头。
I want to change this, but I don't know how.
我想改变这个,但我不知道如何。
Here is the original code:
这是原始代码:
registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
tick(RIGHT);
}
}, "right", KeyStroke.getKeyStroke('d'), WHEN_IN_FOCUSED_WINDOW
);
I have to change it to something like this, but when run, it doesn't work:
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT);
我必须将其更改为这样的内容,但是在运行时,它不起作用:
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT);
KeyStroke.getKeyStroke("RIGHT");
KeyStroke.getKeyStroke("RIGHT");
回答by nIcE cOw
Do start the program by pressing the DOWNARROW KEY
, to watch the string first. Here have a look at this example program :
按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);
}
}