【问题标题】:KeyListener with focus not functioning具有焦点的 KeyListener 不起作用
【发布时间】:2018-04-19 00:55:48
【问题描述】:

我正在向我的代码添加一个关键侦听器,但它没有响应。我不知道这个问题是不是多余的,但是关于类似问题的其他问题都说我应该专注于组件。但是,正如您在此处看到的那样,我尝试过这样做,但它不起作用。我还有一个线程正在运行来渲染我的(非常糟糕的)游戏,这可能是个问题,但我还是不知道。

private GamePanel() {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //get screen dimensions. 

        myImage = new BufferedImage((int) screenSize.getWidth(), (int) screenSize.getHeight(), BufferedImage.TYPE_INT_RGB);
        myBuffer = myImage.getGraphics();
        Player p = new Player(400, 500);
        p.draw(myBuffer);
        abc = new Player(400, 500);
        this.addKeyListener(new Key());
        setFocusable(true);
        this.requestFocus();

    }
public void init() {
    JFrame frame = new JFrame("im bad at coding");
    frame.setLocation(0, 0);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(this);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setUndecorated(false);
    frame.setVisible(true);
    //ive tried to request focus and set focusable here, but no results
    new Thread(this).start(); 

}

【问题讨论】:

  • requestFocus 方法都不能保证成功,有许多条件可能会阻止组件获取焦点 - 唯一“可靠”的解决方案是使用 Key Bindings API,它是预先设计的, 来解决这个问题

标签: java focus keylistener


【解决方案1】:

我认为这可能是由于

A) Not initializing your Game object at all when creating the JFrame
B) Not properly embedding your key listener 

试试这个:

public static void main(String[] args) {
    GamePanel panel = new GamePanel(); //Call your init methods to initialize the panel only, not the jframe
    //Initialize the key listener object either implemented in the game panel itself, or initialized inside of the panel
    new Thread(panel).start(); 
    JFrame frame = new JFrame("im actually not that bad at coding");
    frame.setLocation(0, 0);
    frame.add(panel);
    frame.addKeyListener(panel.getKeyListener()); //Or addListener, i am doing this not on an IDE
    frame.setDefaultCloseOperation(JFrame.BLOW_UP_SYSTEM_ON_EXIT);
    //Optional, just click the frame: frame.setFocus(true);
    frame.pack();
    frame.setVisible(true);
}

【讨论】:

    猜你喜欢
    • 2011-09-09
    • 2013-10-22
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多