我正在尝试编写一个响应玩家键入的键的游戏小程序。我正在尝试使用键绑定来实现此目的。但我无法让它发挥作用。 applet(目前它的一点点)似乎在Appletviewer中正确显示,但是当我按下键时没有任何反应。我无法在浏览器中测试它,因为它并不总能在浏览器中正确显示。
我在Ubuntu上运行Sun Java 6。我设法找到一个Ubuntu错误,其中iBus将阻止键盘输入到applet。但是,我没有运行iBus,而且我已经能够将键盘输入与其他小程序一起使用(不是由我编写的)。
这是迄今为止的代码
public class AlxTestVersion extends JApplet {
private GridBagLayout layout;
private GridBagConstraints layoutConstraints;
private JPanel mainPanel;
public void init() {
this.setLayout ( new FlowLayout(FlowLayout.LEFT) );
//Main frame.
mainPanel = new JPanel();
layout = new GridBagLayout();
layoutConstraints = new GridBagConstraints();
layoutConstraints.anchor = GridBagConstraints.NORTHWEST;
layoutConstraints.fill = GridBagConstraints.NONE;
mainPanel.setLayout(layout);
mainPanel.setBackground(Color.pink);
getContentPane().add(mainPanel);
//Map display
JPanel leftPanel = new JPanel();
GlobalData.mainMap = new MapCanvas(9);
addComponent(GlobalData.mainMap, 0, 0, 1, 1);
/*
Define other components...
*/
}
public class MapCanvas extends JPanel {
private int tileSize;
private int mapTileWidth;
private int mapOffset;
private int mapDim;
private MapSquare screenTiles[];
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon testImage = new ImageIcon("tiles/test_land.gif");
int x,y;
for (x=0;x<mapTileWidth;x++) {
for (y=0;y<mapTileWidth;y++) {
g.drawImage(testImage.getImage(), x*tileSize + mapOffset, y*tileSize + mapOffset, this);
}
}
}
public MapCanvas(int numTiles) {
//Set up window
tileSize = 48;
mapTileWidth = numTiles;
mapOffset = 4;
mapDim = (tileSize * mapTileWidth) + (2 * mapOffset);
Dimension dim = new Dimension(mapDim, mapDim);
this.setPreferredSize(dim);
this.setMinimumSize(dim);
this.setMaximumSize(dim);
this.setLayout( new GridLayout(numTiles, numTiles, 0, 0) );
this.setBackground(Color.black);
screenTiles = new MapSquare[numTiles^2];
//Map-related actions
InputMap im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = this.getActionMap();
AbstractAction north = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Just for testing", "testing",
JOptionPane.PLAIN_MESSAGE);
}
};
am.put("North", north);
im.put(KeyStroke.getKeyStroke('2'), "North");
im.put(KeyStroke.getKeyStroke('i'), "North");
}
}
关于我所使用的和在不同地方找到的工作示例之间的唯一区别是,在将击键映射到动作之前,它们会将键击添加到inputmap。我尝试切换订单,但似乎没有任何效果。
谁能看到我在这里做错了什么?我只知道我错过了一些明显的东西。
答案 0 :(得分:1)
在我点击窗口之前,你的代码对我(在Mac上)也不起作用。在init()中添加以下内容似乎有所帮助(但是not totally reliable):
GlobalData.mainMap.requestFocus();
按键时,您的小程序窗口可能没有焦点。
尝试将此添加到您的init():
GlobalData.mainMap.addFocusListener(new FocusDebugger("canvas"));
this.addFocusListener(new FocusDebugger("applet"));
这是FocusDebugger:
public static class FocusDebugger implements FocusListener {
private final String name;
public FocusDebugger(String name) {
this.name = name;
}
public void focusGained(FocusEvent focusEvent) {
System.out.println(name + ".focusGained");
}
public void focusLost(FocusEvent focusEvent) {
System.out.println(name+".focusLost");
}
}