requestFocusInWindow在Mac OS上工作但在Windows操作系统上没有(Java)

时间:2015-04-07 10:33:04

标签: java windows macos swing behavior

我遇到requestFocusInWindow()的问题。前几天我遇到了一些keyinputs的问题,并设法推断它与组件没有关注有关,因此它从未感觉到键输入。我让它在我的macbook上运行,但现在当我在我的PC上尝试代码时,它没有响应(就像我之前添加requestFocusInWindow一样)。

代码示例:

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();    
    }
}

Keyinput功能:

    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);
    }

还有一些功能限制在移动中,但是这些功能没有响应!

谢谢:)

0 个答案:

没有答案