关键事件仅有时注册

时间:2013-06-02 17:33:45

标签: java swing events keyevent key-events

老实说,我不知道我做错了什么。

有时,关键事件会记录,有时则不会 我的意思是,有时当我运行Frogger2时,我会注册事件,有时甚至没有。

当关键事件注册与否时,似乎完全随机。通常如果我暂时不测试任何东西并运行Frogger2事件注册,当我关闭它并重新运行完全相同的程序时,我没有事件。

请帮忙。

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class Frogger2 extends JPanel {

public static JFrame frame;
public static Frogger2 F;

public Frogger2() {}

public Dimension getPreferredSize() { return new Dimension(500,500); }
public void paintComponent(Graphics g) { super.paintComponent(g); }


private int fdir;

public void moveLeft() {
    travel(2);
}
public void moveRight() {
    travel(0);
}
public void moveUp() {
    travel(3);
}
public void moveDown() {
    travel(1);
}
private void travel(int ddd) {
    System.out.println(ddd);
}


private boolean step() {
    System.out.println("FDIR: "+fdir);
    return true;
}

public void start() {
    fdir = 2;
    while(true) {
        boolean a = step();
        if (!a) break;
        try {
            Thread.sleep(25);
        } catch(Exception e) {}
    }
}

public static void main(String[] args) {
    frame = new JFrame("Frogger");

    F = new Frogger2();
    F.setDoubleBuffered(true);
    frame.add(F);
    frame.pack();
    frame.setVisible(true);
    frame.setResizable(false);
    JPanel abc = (JPanel)frame.getContentPane();
    abc.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left");
    abc.getActionMap().put("left", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {F.moveLeft();}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right");
    abc.getActionMap().put("right", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {F.moveRight();}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("UP"), "up");
    abc.getActionMap().put("up", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {F.moveUp();}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "down");
    abc.getActionMap().put("down", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {F.moveDown();}
    });

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    F.start();

}

}

1 个答案:

答案 0 :(得分:5)

这个问题通常发生在焦点在面板上,每次按任何键都要确保面板处于对焦状态。
您将需要查看Java教程,以便在评论中提及Key Bindings作为@camickr的一个很好的概述。 另请查看question回答@mKorbel(非常感兴趣的答案)。

Key Bindings中感兴趣的是:当你按下 Ctrl + Shift + Space 程序执行一些操作时,它非常有趣且高度建议使用Key Bindings,也可以在堆栈上看到我的first question是关于这个主题的。

你的代码我做了一些改动:

  • KeyListener每按一次键,焦点就会出现在面板上。
  • MouseListener当鼠标进入面板或鼠标点击面板时,焦点将再次出现在面板上。
  • FocusListener:了解面板是否具有焦点。

以下是代码:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class MovingJPanel {

    public static void main(String[] args) {
    JFrame frame = new JFrame("Frogger");

    frame.pack();
    frame.setVisible(true);
    frame.setResizable(true);
    frame.setLocationRelativeTo(null);
    frame.setSize(400,400);
    JPanel abc = new JPanel();
    abc.setBackground(Color.CYAN);
    abc.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left");
    abc.getActionMap().put("left", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("LEFT");}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right");
    abc.getActionMap().put("right", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("ROIGHT");}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("UP"), "up");
    abc.getActionMap().put("up", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("UP");}
    });
    abc.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "down");
    abc.getActionMap().put("down", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("DOWN");}
    });

    abc.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            System.out.println("Focus Gained");
        }
        @Override
        public void focusLost(FocusEvent e) {
            System.out.println("Focus Lost");
        }  
});
    abc.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            JPanel p = (JPanel)e.getSource();
            p.requestFocus();
        } 
});

    abc.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
           JPanel p = (JPanel)e.getSource();
            p.requestFocus();
        }

});
    frame.getContentPane().add(abc,"Center");
    frame.getContentPane().add(new JButton("Click Me"),"North");
    abc.requestFocusInWindow();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}