在 JFrame 中获取输入焦点时遇到问题

Trouble getting Input Focus in JFrame(s)

这是(简化的)JPanel class:

import java.awt.Graphics;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class Preface extends JPanel{


  public Preface(){
    this.addKeyListener(new Controls());
    this.requestFocusInWindow();
    System.out.println(this.hasFocus());//false
    this.repaint();
  }

  public void paintComponent(Graphics g){
    super.paintComponent(g); 

    g.drawImage(Tetris.getTexture("PrefacePoster.jpg"), 0, 0, 420, 556, null);
  }

}

我在让关键事件起作用时遇到了问题,并意识到我的面板一开始就没有获得输入焦点,因此没有生成任何关键事件。

我试过 grabFocus()、requestFocusInWindow()、requestFocus() 等,但 hasFocus() 总是 returns 错误。

为什么我的 JPanel 没有获得输入焦点?有什么办法可以强迫他们这样做吗?

默认情况下组件不可聚焦。所以你需要:

setFocusable( true );

在构造函数中。其他方法 requestFocusInWindow() 仅适用于可见 JFrame 上的可见组件。从构造函数中调用该方法将不会执行任何操作。

repaint() 方法相同。该组件尚不可见,因此构造函数中不需要该语句。

not generating any KeyEvents.

您不应该使用 KeyListener 来侦听 KeyEvent。相反,您应该使用 Key BindingsKey Bindings 即使组件没有焦点也能正常工作。