由於聚焦問題,我在Java中的關鍵監聽器遇到了一些麻煩,所以我閱讀了它,許多網站建議使用鍵綁定。 我的代碼在下面,我試圖將空間鍵映射到一個動作TestAction。面板對象只是JPanel的擴展。Java - 代碼編譯但操作不被識別
public class Template_Main {
static Boolean quit = false;
public static void main(String[] args) {
Window window = new Window();
while(!quit) {
window.update();
}
System.exit(0);
}
}
。
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
public class Window {
public Frame frame;
public Panel panel;
public Window() {
frame = new Frame();
panel = new Panel();
Action pressedAction = new TestAction();
Action releasedAction = new TestAction();
pressedAction.setEnabled(true);
releasedAction.setEnabled(true);
panel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),"pressed");
panel.getInputMap().put(KeyStroke.getKeyStroke("released SPACE"),"released");
panel.getActionMap().put("pressed",pressedAction);
panel.getActionMap().put("released",releasedAction);
frame.add(panel);
frame.pack();
}
public void update() {
Logic.update();
updateImages();
sleep();
}
public void updateImages() {
panel.removeAll();
for (int i = 0; i < Imgs.array.size(); ++i) {
Img img = Imgs.get(i);
addImage(img.name, img.x, img.y, img.width, img.height);
}
panel.repaint();
}
public void addImage(String name, int x, int y, int width, int height) {
panel.add(newImageLabel(name, x, y, width, height));
}
public static JLabel newImageLabel(String imageName, int x, int y, int width, int height) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
java.net.URL iconUrl = ClassLoader.getSystemResource("resources/"+imageName);
Image image = toolkit.createImage(iconUrl);
JLabel label = new JLabel(new ImageIcon(image));
label.setBounds(x, y, width, height);
return label;
}
static void sleep() {
try {
Thread.sleep(Math.round(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
。
import javax.swing.JFrame;
public class Frame extends JFrame {
public Frame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle(Config.TITLE);
setResizable(Config.RESIZABLE);
setVisible(true);
}
}
。
import java.awt.Dimension;
import javax.swing.JPanel;
public class Panel extends JPanel {
public Panel() {
setPreferredSize(new Dimension(Config.WIDTH,Config.HEIGHT));
setLayout(null);
setBackground(Config.BG_COLOR);
setFocusable(true);
}
}
。
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class TestAction extends AbstractAction {
public TestAction() {
}
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("ACTION PERFORMED");
}
}
問題是,雖然它編譯沒有錯誤,沒有任何反應,當我按空格鍵。
當你按下空間時,你的面板是否有焦點? –
是的,我相信如此... – k13ran
您的代碼是否太大而無法完整發布?或者可能是一個簡短的可編譯示例?我沒有看到任何明顯的你在這裏做錯了。 –