【发布时间】:2019-12-11 16:58:16
【问题描述】:
我目前的键盘按钮可以正常工作。我想知道当我按方向键时是否可以在两张图片之间切换。我的图片被放在名为 thing 的 JLabel 中。 JLabel 正在移动,我需要做的就是让它在按下键时交替显示图片。
class start {
start() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(1210, 700);
mainFrame.setLocation(new java.awt.Point(150, 30));
mainFrame.setLayout(null);
mainFrame.setFocusable(true);
mainFrame.setFocusTraversalKeysEnabled(true);
mainFrame.setIconImage(new ImageIcon("images\\sword.png").getImage());
JLabel thing = new JLabel();
thing.setIcon(new ImageIcon("image\\walkdown.png"));
thing.setBounds(300, 300, thing.getPreferredSize().width, thing.getPreferredSize().height);
InputMap inputMap = thing.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = thing.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "move.up");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "move.up");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "move.down");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "move.down");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "move.left");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "move.left");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "move.right");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "move.right");
actionMap.put("move.up", new ThingAction(thing, new Point(0, -5)));
actionMap.put("move.down", new ThingAction(thing, new Point(0, 5)));
actionMap.put("move.left", new ThingAction(thing, new Point(-5, 0)));
actionMap.put("move.right", new ThingAction(thing, new Point(5, 0)));
mainFrame.add(thing);
mainFrame.setVisible(true);
}
public class ThingAction extends AbstractAction {
private JLabel thing;
private Point delta;
public ThingAction(JLabel thing, Point delta) {
this.thing = thing;
this.delta = delta;
}
@Override
public void actionPerformed(ActionEvent arg0) {
thing.setLocation(thing.getX() + delta.x, thing.getY() + delta.y);
}
}
}
【问题讨论】:
-
"我想知道我是否可以将图片从 1 更改为 1 和返回..." 一个到什么?请写完整的句子。否则很难说出你在问什么。
-
哪张照片?依附于什么?什么时候改?
-
@PM77-1 我添加了更多细节。但是我的图片被添加到 JLabel 中,我希望它在按下键盘上的方向键时改变。图片只是一个简单的png。
-
那么,你想在
walkdown.png和其他一些人之间切换吗?