requestFocusInWindow在Mac OS上工作,但不在Windows OS(Java)上工作
我对requestFocusInWindow有问题。前几天,我在keyinputs方面遇到了一些问题,并设法推断出这与组件没有被聚焦有关,因此它从未感觉到keyinputs。我让它在我的macbook上运行,但是现在当我在我的PC上尝试代码时,它没有像我添加requestFocusInWindow之前那样响应 代码示例:requestFocusInWindow在Mac OS上工作,但不在Windows OS(Java)上工作,java,windows,macos,swing,behavior,Java,Windows,Macos,Swing,Behavior,我对requestFocusInWindow有问题。前几天,我在keyinputs方面遇到了一些问题,并设法推断出这与组件没有被聚焦有关,因此它从未感觉到keyinputs。我让它在我的macbook上运行,但是现在当我在我的PC上尝试代码时,它没有像我添加requestFocusInWindow之前那样响应 代码示例: class TetrisFrame extends JFrame { private Board board; private TetrisComponent
class TetrisFrame extends JFrame {
private Board board;
private TetrisComponent frame;
public TetrisFrame(Board board) {
super("Tetris");
this.board = board;
this.frame = new TetrisComponent(board);
JComponent.setDefaultLocale(Locale.ENGLISH);
Locale.setDefault(Locale.ENGLISH);
JButton close = new JButton("Exit");
JMenuBar menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
menuBar.add(close);
close.addActionListener(e -> {
int selectedOption = JOptionPane.showConfirmDialog(null, "Do You want to close the game?\n" + "All progress will be lost!",
"Exit game", JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
System.exit(0);
}
});
this.setLayout(new BorderLayout());
this.add(frame, BorderLayout.CENTER);
this.pack();
this.setSize(frame.getPreferredX(board), frame.getPreferredY(board));
this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setFocusable(true);
frame.requestFocusInWindow();
}
}
按键输入功能:
private final Action moveLeft = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
board.moveLeft();
}
};
private final Action moveRight = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
board.moveRight();
}
};
public void setKeyBindings() {
this.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "moveLeft");
this.getActionMap().put("moveLeft", moveLeft);
this.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "moveRight");
this.getActionMap().put("moveRight", moveRight);
}
有更多的功能绑定到运动,但正是这些功能没有响应
谢谢:您可以通过使用getInputMapJComponent来解决这个问题。当聚焦窗口中的工作正常时!非常感谢: