我正在尝试编写一个响应玩家键入的键的游戏小程序。我正在尝试使用键绑定来完成此操作。但我无法让它工作。小程序(目前只有很少的一部分)似乎在 Appletviewer 中正确显示,但是当我按下键时没有任何反应。我无法在浏览器中对其进行测试,因为它并不总是在浏览器中正确显示。
我在 Ubuntu 上运行 Sun Java 6。我设法找到提到 iBus 会阻止键盘输入到小程序的 Ubuntu 错误。但是,我没有运行 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");
}
}
关于我所使用的和在不同地方找到的工作示例之间我能找到的唯一区别是它们在将击键映射到动作之前将击键添加到输入映射。我尝试切换顺序,但似乎没有任何效果。
谁能看到我在这里做错了什么?我只知道我遗漏了一些明显的东西。