Tôi đang cố gắng làm điều gì đó khi một trong các phím mũi tên được nhấn bằng cách sử dụng KeyListener trong lớp JPanel của tôi. Đây là mã của tôi:Keylistener không hoạt động với JPanel
public class TestPanel extends JPanel implements KeyListener{
public TestPanel(){
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
Phương pháp chính của tôi thêm một trường hợp mới của bảng này vào khung và hiển thị nó. Tôi có cần phải thêm keylistener vào JFrame không? Trong trường hợp của tôi, điều này sẽ khó khăn và không hiệu quả, vì vậy tôi muốn làm cho nó hoạt động với JPanel này nếu có thể. Có ai biết tôi đang làm gì sai không?
EDIT: Key Bindings mã mà không làm việc, hoặc:
public class GamePanel extends JPanel implements ActionListener{
//Constructor
public GamePanel(){
setupKeyBinding();
this.setFocusable(true);
this.requestFocusInWindow();
}
private void setupKeyBinding() {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inMap = getInputMap(condition);
ActionMap actMap = getActionMap();
inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
actMap.put("Left", new leftAction());
}
private class leftAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
}
public void actionPerformed(ActionEvent e) {
//some other game info
}
}
Có thể ai đó cho tôi biết lý do tại sao việc doesnt này một trong hai? (người nghe hành động thứ hai của tôi dành cho những thứ khác cần thiết cho trò chơi của tôi)
Một ý tưởng khác có thể là tạo một lớp bên trong và sử dụng một cái gì đó như: "this.addKeyListener (lớp bên trong/lớp bên trong vô danh);" – ObedMarsh
có thể trùng lặp của [java keylistener not called] (http://stackoverflow.com/questions/8482268/java-keylistener-not-called) –