java 箭头语法,Java:使用带箭头键的按键

博客讲述了如何修改代码,将KeyStroke中的'a'替换为'RIGHT'来响应右箭头键。原始代码使用KeyStroke.getKeyStroke('d'),博主尝试改为KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT)或KeyStroke.getKeyStroke(RIGHT),但运行不成功。示例程序展示了如何在Java Swing中注册键盘动作,并根据用户按下UP、DOWN、LEFT、RIGHT键改变画布上的坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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("RIGHT");

解决方案

Do start the program by pressing the DOWN ARROW KEY, to watch the string first. Here have a look at this example program :

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值