gpt4 book ai didi

java - 将 keyAdapter 替换为键绑定(bind)

转载 作者:搜寻专家 更新时间:2023-11-01 02:47:48 27 4
gpt4 key购买 nike

我如何在这段代码中使用键绑定(bind),因为键适配器不能正常工作?我已经查看了键绑定(bind)的文档,但我不明白如何执行此操作。

private class KeyLis extends KeyAdapter 
{
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
up = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_RIGHT:
right = true;
break;
}
}

@Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
up = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
break;
}
}
}

谢谢

最佳答案

您需要将相应的键添加到应用 KeyBinding 的组件的 InputMap 中,如下所示:

panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("pressed UP"), "pressedUPAction");
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("released UP"), "releasedUPAction");

panel.getActionMap().put("pressedUPAction", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("UP Arrow Pressed");
}
});

panel.getActionMap().put("releasedUPAction", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("UP Arrow Released");
}
});

看看这个工作示例:

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

public class SmallExample {

private JButton button;
private JPanel panel;

private void displayGUI() {
JFrame frame = new JFrame("Small Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

panel = new JPanel() {
@Override
public Dimension getPreferredSize() {
return (new Dimension(100, 100));
}
};
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("pressed UP"), "pressedUPAction");
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("released UP"), "releasedUPAction");

panel.getActionMap().put("pressedUPAction", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("UP Arrow Pressed");
}
});

panel.getActionMap().put("releasedUPAction", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("UP Arrow Released");
}
});

frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new SmallExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

关于java - 将 keyAdapter 替换为键绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com